2API的数据访问困难使用ForkJoin访问

Difficulty in accessing data of 2 API Using ForkJoin to access

我正在尝试在我的 angular 应用程序

上访问 2 API
  1. https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json

  2. https://www.fantasylabs.com/api/sportevents/3/2019_06_17

我正在使用 forkjoin 异步访问两个数据的数据

这是我的 api.component.ts

代码

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, forkJoin } from 'rxjs';

@Component({
  selector: 'app-mlb-api',
  templateUrl: './mlb-api.component.html',
  styleUrls: ['./mlb-api.component.css']
})
export class MlbApiComponent  {

loadedCharacter: {};
  constructor(private http: HttpClient) { }

  ngOnInit() {
    let character = this.http.get('https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json');
    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 = results[0];
    });
  }
}


我正在尝试从第一个 API 获得名称 属性,从第二个 API 获得 EventID 属性。

这是我的 html 代码。

   <td>{{loadedCharacter.name}}</td>
    <td>{{loadedCharacter.EventId}}</td>

在输出中我得到

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

我可以使用此命令检索页面上的所有 json 数据

{{loadedCharacter | json}}

我应该进行哪些更改才能单独检索所有数据?

您应该像这样更改您的代码:

有这样的loadCharcters

loadedCharacter: {name: string, eventId: string} = <{name: string, eventId: string}>{};

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 => {

      this.loadedCharacter.name = results[0][0].name;
      this.loadedCharacter.EventId = results[1][0].EventId;
      console.log(results[0][0].name);
    });
  }

<td>{{loadedCharacter.name}}</td>
<td>{{loadedCharacter.EventId}}</td>

我已经更新了 stackblitz。

查看 stackblitz 中的演示 - https://stackblitz.com/edit/angular-8npc19?file=app/button-overview-example.ts

results[1]是请求返回的数组https://www.fantasylabs.com/api/sportevents/3/2019_06_17

另一方面,第一个的结果是一个只有一个 属性 "events" 的对象,所以我认为你应该多考虑一下这个映射:

...
      (results[0] as any).name = results[1];
      this.loadedCharacter = results[0];
...