Используя ForkJoin, я пытаюсь получить доступ к данным из 2 API
https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json
https://www.fantasylabs.com/api/sportevents/3/2019_06_17
Я использую forkjoin для асинхронного доступа к данным обоих данных. Я могу успешно получить доступ к homeTeamName,awayTeamName, но при доступе к линиям я получаю сообщение об ошибке
core.js:1521 ERROR ReferenceError: allline is not defined
API.component.html
<table class = "table table-striped table-condensed table-hover">
<div class = "container">
<div class = "row">
<div class = "col-xs-4">
<div class = "table-responsive">
<table summary = "This table shows how to create responsive tables using Bootstrap's default functionality" class = "table table-bordered table-hover">
<thead>
<tr>
<th>Information</th>
<th>HomeTeam vs AwayTeam</th>
<th>Line</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<div class = "container">
<div class = "row">
<ng-container *ngFor = "let n of allhomeTeamName">
<tr><td>{{n}}</td></tr>
</ng-container>
</tbody>
<tbody>
<tr>
<div class = "container">
<div class = "row">
<ng-container *ngFor = "let n of allawayTeamName">
<tr><td>{{n}}</td></tr>
</ng-container>
</tbody>
</div>
</div>
<div class = "container">
<div class = "row">
<ng-container *ngFor = "let n of allline">
<tr><td>{{n}}</td></tr>
</ng-container>
</tbody>
</div>
</div>
код api.component.ts
import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http'
import {forkJoin} from 'rxjs';
import {map} from 'rxjs/operators';
@Component({
selector: 'app-mlb-api',
templateUrl: './mlb-api.component.html',
styleUrls: ['./mlb-api.component.css']
})
export class MlbApiComponent {
loadedCharacter: { homeTeamName:string, awayTeamName:string, line:string, EventId:string, visitorTeam:string,homeTeam:string} = <{homeTeamName:string, awayTeamName:string, line:string, EventId:string, visitorTeam:string,homeTeam:string}>{};
allhomeTeamName;
allawayTeamName;
allline;
constructor(private http: HttpClient) {
}
ngOnInit() {
let character = this.http.get('https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json')
.pipe(map((re: any) => re.events));
let characterHomeworld = this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17');
forkJoin([character, characterHomeworld]).subscribe(results => {
//(results[0] as any).name = results[1];
//this.loadedCharacter.name = results[0].name;
this.loadedCharacter.homeTeamName = results[0].homeTeamName;
this.loadedCharacter.awayTeamName = results[0].awayTeamName;
this.loadedCharacter.line = results[0][0].offers[0].outcomes[0].line;
//this.loadedCharacter.line = results[1][0].VisitorTeam;
//this.loadedCharacter.line = results[1][0].HomeTeam;
//this.loadedCharacter.EventId = results[1][0].EventId[1];
this.allNames = results[0].map(r => r.name);
console.info(this.allNames);
this.allhomeTeamName = results[0].map(r => r.homeTeamName);
console.info(this.allhomeTeamName);
this.allawayTeamName = results[0].map(r => r.awayTeamName);
console.info(this.allawayTeamName);
this.allline = results[0].map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line);
console.info(allline);
this.allEventId = results[1].map(r => r.EventId);
console.info(results[1][0]);
this.allvisitorTeam = results[0].map(r => r.VisitorTeam);
console.info(this.allvisitorTeam);
this.allawayTeam = results[0].map(r => r.AwayTeam);
console.info( this.allawayTeam);
});
}
}
Как я могу решить эту ошибку?
Это дает {EventDetails: null, EventId: 4436180, SportId: 3, VisitorTeam: "Tampa Bay Rays", HomeTeam: "New York Yankees", …}
Но я даю undefined, если пытаюсь получить доступ к данным с помощью this.loadedCharacter.EventId = results[1][0].EventId;
Я выяснил EventId, можете ли вы проверить метку?
этикетка? Не вижу ничего связанного с лейблом.
Я обновил свой код, у меня возникли проблемы с отображением строки на моей странице
Просто предложение: с помощью forkJoin вы можете заменить результаты в своей подписке на ([draftKingResults, fantasyLabsResults])
, чтобы вам не приходилось делать эту results[0]
чепуху. Выглядит намного читабельнее.
Нужно ли их сначала объявлять? Можете быть более конкретными?
Вы можете иметь свой код следующим образом:
ngOnInit() {
let character = this.http.get('https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json')
.pipe(map((re: any) => re.events));
let characterHomeworld = this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17');
forkJoin([character, characterHomeworld]).subscribe(([draftkingsResp, fantasylabsResp]) => {
this.allNames = draftkingsResp.map(r => r.name);
//console.info(this.allNames);
this.allhomeTeamName = draftkingsResp.map(r => r.homeTeamName);
//console.info(this.allhomeTeamName);
this.allawayTeamName = draftkingsResp.map(r => r.awayTeamName);
//console.info(this.allawayTeamName);
this.alllabel = draftkingsResp.map(r => r.offers).flat().map(o => o.label);
//console.info(this.alllabel);
this.allline = draftkingsResp.map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line);
console.info(this.allline);
//this.allline will have 'undefined' as well
//if you want then you can filter
this.allline = this.allline.filter(l => !!l);
console.info(this.allline);
});
}
Посмотреть стек-блиц - https://stackblitz.com/edit/angular-8npc19?file=app%2Fbutton-overview-example.ts
Серьезно, гений!!
Эй, друг, одна проблема с доступом к данным — stackoverflow.com/questions/56740175/…. Если вы свободны, проверьте. Спасибо
@Karan Я думаю, что к тому времени, когда я его увидел, на твой вопрос уже был дан ответ.
Что вы получите, если сделаете
console.info(results[1][0])
? Изучите набор результатов и посмотрите, как он структурирован.