我正在尝试通过服务从 API 获取数据。然后从模块内部记录它,稍后将在列表中显示它。该变量显示在服务的 console.log 中,但当我尝试将其记录到模块中时却没有显示
我之前用 ionic 做过同样的设置,我认为 Angular 的工作原理是一样的,但这里的情况并非如此。我已经通过错误处理扩展了 .subscribe 函数,但没有显示错误。我只是不知道该去哪里寻找。
api.service.ts
getPlacesData(): any {
let result = this.http.get(`${this.apiUrl}/places`, this.httpOptions).pipe(
map(response => {
console.log(response['data']);
response['data'];
})
);
return result;
}
}
测试仪表板.component.ts
constructor(private breakpointObserver: BreakpointObserver, private apiService: ApiService) {}
getPlacesData() {
this.apiService.getPlacesData().subscribe(
(placesData: Observable<any>) => {
console.log(placesData);
this.placesData = placesData;
console.log(this.placesData);
},
(error: string) => {
console.log('Received an errror: ' + error);
}
);
}
ngOnInit() {
this.getPlacesData();
}
}
我希望第二个和第三个 console.log 具有与第一个相同的输出,但这些输出是“未定义”而不是:
(15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}、{…}、{…}、{…}、{…}]
最佳答案
问题是您试图同步返回一个值。 Angular https 请求是异步的。请这样对待他们。你的函数应该返回 Observable。在 html 模板中使用异步管道来访问之后的数据。
getPlacesData(): Observable<Places[]> {
return this.http.get<Places[]>(`${this.apiUrl}/places`, this.httpOptions).pipe(
map(response => response['data']),
);
}
}
关于angular - 如何修复 Angular 中的数据无法从服务传输到模块的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57872260/