Angular 6-无法处理来自web api的数据

Angular 6-无法处理来自web api的数据,angular,typescript,Angular,Typescript,我正在尝试处理Angular 6中api中的一些数据。但是,即使我可以在网络选项卡中看到下面的数据正在返回,我也无法在该调用完成后处理数据 服务返回的我的数据: {"profile": "German DJ and producer based in Berlin. He is the founder of a label."} 我的回执: public fetchData(): Observable<DiscogsRecord> { return this.h

我正在尝试处理Angular 6中api中的一些数据。但是,即使我可以在网络选项卡中看到下面的数据正在返回,我也无法在该调用完成后处理数据

服务返回的我的数据:

    {"profile": "German DJ and producer based in Berlin. He is the founder of a label."}
我的回执:

  public fetchData(): Observable<DiscogsRecord> {
    return this.http.get(this.url).pipe(
    map(response => response["profile"]),
    catchError(this.errorHandler("Error loading music data.", []))
  );
 }
我的ngOnInit:

ngOnInit() {
this.recs = [];
this.dataService.fetchData().subscribe(records => (this.recs = records));
console.log(this.recs);

... etc

当我记录this.recs时,我没有得到任何数据,只有一个空数组:[]。我做错了什么?

只要在您的服务中返回响应

 return this.http.get(this.url).pipe(
    map(response => response)
您需要在订阅中访问

this.dataService.fetchData().subscribe((records) => { 
 this.recs = records;
 console.log(this.recs[0].profile);
});

您在哪里进行日志记录的问题

this.dataService.fetchData().subscribe(records => (this.recs = records));
console.log(this.recs);
Http请求是异步的,所以当您调用fetchData时,它会返回一个可观察的,然后执行日志语句。此时,它还没有检索到数据。当检索到数据时,它调用subscribe中的代码

this.dataService.fetchData().subscribe(records => 
     {
        this.recs = records;
        console.log(this.recs);
      });
因此,您需要将日志移动到订阅中

this.dataService.fetchData().subscribe(records => 
     {
        this.recs = records;
        console.log(this.recs);
      });

您尝试过这个mapresponse:DiscogsRecord=>response.profiles吗?当然,它们是异步的它一直在工作。谢谢答案不一样吗?