等待以角度2加载对象

时间:2018-02-20 23:09:13

标签: javascript angular typescript

当我从服务分配数据时,如何操作我的另一个组件中的数据。我的视图可以异步读取此数据,但我无法通过console.log读取属性。每当我看到'undefined'。在此console.log之后,我需要加载另一个路径/组件并返回到之前的视图  显示我的请求。这是我的代码: Frienddetails.component.ts

   export class FrienddetailsComponent implements OnInit {
      name: string;
      id: number;
      gameId: any = [];
      serviceArray: any = [];
      objectDataService: any = [];
      objectDataArray: any = [];

      constructor(public dataService: DataService,
        public friendService: FriendService,
        private route: ActivatedRoute) {
          this.name = this.route.snapshot.params['name'];
          this.serviceArray = this.dataService.getDataService();

      }

      fetchListOfMatch(query) {
        this.friendService.getListOfMatch(query).subscribe((data) => {
          this.objectDataArray.push(data.matches.length);
        });
      }

      getMatchGameId() {
        for (let i of this.objectDataArray) {
          let k = i.matches.length;
          for (let c = 0; c < k; c++) {
            this.gameId.push(i.matches[c].gameId);
          }
        }
      }

      ngOnInit() {
        console.log(this.serviceArray);
        this.id = this.friendService.getIdByName(this.name, this.serviceArray);
        this.friendService.id = this.id;
        this.friendService.query = `${this.friendService.apiUrl}${this.friendService.id}?season=11&${this.friendService.apikey}`;
        this.fetchListOfMatch(this.friendService.query);
      }
    }

app.component.ts

export class AppComponent implements OnInit {

  friends= FRIEND;
  myDataFromDb: any[] = [];
  SortedArray: any[] = [];
  constructor(public dataService: DataService) {
}

  private getDataFromDb(query) {
   /* function compare(a,b) {
      if (a.id < b.id)
        return -1;
      if (a.id > b.id)
        return 1;
      return 0;
    }*/
      this.dataService.getData(query).subscribe((data) =>
      {




       this.dataService.data.push(data);
       this.dataService.serviceResponse = data;
      });
    }

  ngOnInit() {

    for (let i of this.dataService.friends) {
        this.dataService.query = `${this.dataService.apiUrl}${i.nick}?${this.dataService.apikey}`;

        this.getDataFromDb(this.dataService.query);

      }




        }
}

1 个答案:

答案 0 :(得分:0)

听起来你只需要向FrienddetailComponent添加一个ngOnChanges生命周期钩子,它可以检查它是否有一个有效的输入并相应地发出一个额外的服务请求。

向FrienddetailsComponent添加@Input并从AppComponent传入预期值。

文档:https://angular.io/guide/component-interaction