Angular 2 api data



我想从 Riot API 获取数据并将其显示在 html 视图中。但是,我无法在我的变量中"保存"这些数据。控制台日志显示空数组。我只能在函数范围内看到 json 数据。我想,我没有正确使用可观察函数,我错了吗?这是我的组件。

    import { Component, OnInit } from '@angular/core';
import { FRIEND } from '../../services/_friends/mock-friends';
import { APIKEY } from '../../services/_lolapi/apikey';
import { Http, Response } from '@angular/http';
import { KeysPipe } from '../../pipes/key';
import { JsonPipe } from '@angular/common';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'app-friends',
  templateUrl: './friends.component.html',
  styleUrls: ['./friends.component.css']
})
export class FriendsComponent implements OnInit {
friends = FRIEND;
apikey = APIKEY;
nick: string[];
query: string;
  private apiUrl =
  'https://eun1.api.riotgames.com/lol/summoner/v3/summoners/by-name/';
  data: Array<string> = [];
  constructor(private http: Http) {

   }
getFriendData(query) {
return this.http.get(query)
  .map((res: Response) => res.json());
}
getContacts() {
  this.getFriendData(this.query).subscribe(data => {
    this.data = data;
    console.log(this.data);
  });
}

  ngOnInit() {
    for (let i of this.friends) {
        this.query = `${this.apiUrl}${i.nick}${this.apikey}`;
  this.getFriendData(this.query);
   this.getContacts();
console.log(i.nick);
    }
  }
}

您不需要this.getFriendData(this.query) ngOnInit,就像在下一行中调用的包装getFriendData一样getContacts

现在,您的API返回SummonerDTO - 一个复杂的对象,并且您正在尝试将其存储为数组?这似乎不对。此外,它认为您想将每个结果存储在一个数组中,对吗?在这种情况下,您应该使用:

this.data.push(data);

最新更新