[英]http wait for another call finish
scenario :场景:
problem :问题:
http.service.ts sample code : http.service.ts 示例代码:
private isReady = false;
constructor(private httpClient: HttpClient) {
this.init();
}
// pass local data to check user login status
// check the token, expired date etc.
public init() {
// this.httpClient.post to verify user status
// this.isReady = true;
}
// http get request used in other components
public get(url) {
if (this.isReady) {
return this.httpClient.get<any>(this.apiRoot + url);
} else {
// how to wait for init() is done before return in here?
return this.httpClient.get<any>(this.apiRoot + url);
}
}
You can try like this.你可以这样试试。 In app component
在应用程序组件中
async ngOnInit() {
await this.http.init(); // wait until init complete
// Then call your other things
}
HttpService.ts HttpService.ts
public async init(): Promise<void> {
await this.httpClient
.get<any>(this.apiRoot + "assets/user.json")
.toPromise()
.then(s => {
console.log("init completed");
});
}
This is the code sandbox link这是代码沙箱链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.