Angular/RXJS-等待AJAX请求完成


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进行此操作。

类似这样的东西:

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

Subscribe附带了err和success函数回调。您可以在成功回调中调用getStructureType。只有在请求完成时才会调用success回调。

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');
}
);

最新更新