只有当我订阅从 Angular 服务内部进行 api 调用的函数时,我才会得到这个,所以订阅该函数的对象是空的。这是我的服务中的代码片段:
getSchedules(): Observable<Schedule[]> {
this.http.get<TempSchedules[]>(this.apiUrl).subscribe(x => this.temp = x);
this.temp.forEach((e, i) => {
// Do something, this loop is never executed because this.temp is empty
});
// Some processing here
return something; }
这是我在服务内部某处的 http.get 函数:
getTempSchedules(): Observable<TempSchedules[]> {
return this.http.get<TempSchedules[]>(this.apiUrl);
}
从上面看,this.temp 是空的。这是为什么?
我在服务构造函数中将上述函数称为
constructor(private http:HttpClient) {
this.getTempSchedules().subscribe(x => this.temp = x);
}
以下是调用服务中该函数的组件的代码片段:
ngOnInit(): void {
this.scheduleService.getTempSchedules().subscribe(x => this.tempSchedules = x);
}
该组件工作正常,因此当我在 html 中使用 value this.tempSchedules 时,它会正确显示。我在这里想念什么?
回答1
它不起作用,因为您没有得到 observable 的工作方式。这是异步过程,您需要在订阅块中才能获得它。如果您想在将响应返回到组件之前对响应做一些时髦的事情,那么您应该使用 map
getTempSchedules(): Observable<Schedule[]> {
return this.http.get<TempSchedules[]>(this.apiUrl)
.pipe(map(res => {
return res.forEach(() => {
// Do something, this loop will be executed
})
})) }
在组件中使用它:
ngOnInit(): void {
this.scheduleService.getTempSchedules().subscribe(x => this.tempSchedules = x);
}