-1

我创建了一个 Angular 服务,它返回一个Observable对象数组,使用offrom rxjs

export class HackfestService {

  constructor(private http: HttpClient) { }

  getHackfests():Observable<HackFestDetails[]>{
    return of([
      {hackfestId: 1, hackfestName: "Hackfest Alpha",hackfestDate: new Date('June 12, 2018'), noOfParticipants: 500, noClearedPre: 100, isFinalResultOut:true, isPreResultOut:true},
      {hackfestId: 2, hackfestName: "Hackfest Beta",hackfestDate: new Date('July 22, 2018'), noOfParticipants: 0, noClearedPre:0 , isFinalResultOut:false, isPreResultOut:false}
    ]);
  }
}

它工作正常,直到我用这样of的实际HttpClient.get()请求替换该部分:

export class HackfestService {

  private hackfestsURL =  'http://localhost:57161/api/Hackfest/GetHackfests';
  constructor(private http: HttpClient) { }

  getHackfests():Observable<HackFestDetails[]>{
    // return of([
    //   {hackfestId: 1, hackfestName: "Hackfest Alpha",hackfestDate: new Date('June 12, 2018'), noOfParticipants: 500, noClearedPre: 100, isFinalResultOut:true, isPreResultOut:true},
    //   {hackfestId: 2, hackfestName: "Hackfest Beta",hackfestDate: new Date('July 22, 2018'), noOfParticipants: 0, noClearedPre:0 , isFinalResultOut:false, isPreResultOut:false}
    // ]);
    return this.http.get<HackFestDetails[]>(this.hackfestsURL);
  }
}

我已经测试了给出 JSON 结果的 URL:

    [{"hackfestId":1,"hackfestName":"Hackfest Alpha","hackfestDate":"2018-06-12T00:00:00","noOfParticipants":100,"noClearedPre":100,"isFinalResultOut":true,"isPreResultOut":true},
    {"hackfestId":2,"hackfestName":"Hackfest Beta","hackfestDate":"2018-07-22T00:00:00","noOfParticipants":0,"noClearedPre":0,"isFinalResultOut":false,"isPreResultOut":false}]

我已将组件中的 observable 订阅为:

ngOnInit(){
    this.getHackfestList();
    this.selectedHackfest = this.allHackfests[0];
  }

  getHackfestList():void{
    //call api and get the list sorted in descending order of festival date
    this.hackfestService.getHackfests().subscribe(items => {
      this.allHackfests = items;
      console.log(this.allHackfests);
    });

    this.allHackfests.sort((x:HackFestDetails, y:HackFestDetails)=>{return y.hackfestDate.getTime()-x.hackfestDate.getTime()} );
  }

console.log()subscribe 方法内部的A 实际上记录了从该方法接收到的 JSON 数据HttpClient.get(),但是该属性this.allHackfests仍然存在undefined,因此当我尝试访问其任何属性时会出错。

Angular 6的官方教程有一个类似的实现,他们声明:

您已经换成了 http.get 并且应用程序继续工作而无需任何其他更改,因为这两个函数都返回一个 Observable

显然,该声明与我在实施中观察到的不一致。还有一些我可能会遗漏的变化吗?

4

1 回答 1

0

这是因为getHackfests()是一个异步函数。

代码不会等待并将执行下一行,因此会出现错误。

您应该将sort部分移动到subscribe.

于 2018-07-10T15:07:42.570 回答