[英]Angular/RXJS - Wait for AJAX request to complete
export class DropDownService {
private dockerURL;
constructor(private infoService: InfoService){
this.infoService.getVersion().subscribe((URL) => {
this.dockerURL = URL;
});
// How to make sure the dockerURL is loaded
// before getStructureType is invoked from other services
}
getStructureType(): Observable<StructureType[]> {
return this.http.get<StructureType[]>(this.dockerURL+'/structureType');
}
}
如何确保在从其他服务调用 getStructureType 之前加载 dockerURL?
switchMap
,您可以利用switchMap
。
像这样的东西:
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
.....
export class DropDownService {
private dockerURL;
constructor(private infoService: InfoService){
}
getStructureType(): Observable<StructureType[]> {
return this.getDockerURL().pipe(
switchMap(url => {
return this.http.get<StructureType[]>(url+'/structureType');
}),
);
}
private getDockerURL(): Observable<string> {
if (this.dockerURL) {
return of(this.dockerURL);
} else {
return this.infoService.getVersion().pipe(
// tap is an operator that is used for side effects, every time this stream emits, we assign it to this.dockerURL. Should only be once.
tap(url => this.dockerURL = url),
);
}
}
}
这样,它可以确保在进行 HTTP 调用之前填充dockerURL
。
订阅带有 err 和 success 函数回调。 您可以在成功回调中调用 getStructureType。 只有在请求完成时才会调用成功回调。
this.infoService.getVersion().subscribe((URL) => {
//...
},
err => { //========> if fails this gets called
console.log(err );
}
suc => { // =======> gets called on success when its successfully executed
this.dockerURL = URL;
this.http.get<StructureType[]>(this.dockerURL+'/structureType');
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.