[英]How to make typescript stream reading code not to proceed before stream is ended?
[英]How to make typescript execute code seqentially?
我的代碼似乎不等待執行某些代碼而走得更遠。
isAdmin(): boolean {
this.getLoggedUser();
this.getRole();
console.log(this.admin);
console.log('isAdmin');
return this.admin;
}
getRole() {
this.httpClient.get<boolean>('/api/has-role-admin').
subscribe((data) => {
this.admin = data;
console.log(this.admin);
console.log('getRole');
}
);
}
控制台結果:
false
isAdmin
true
getRole
我想完成getRole()方法,然后在isAdmin()中完成其余步驟。 我怎么能收到這種行為?
您的代碼是異步的,因為您訂閱了一個可觀察的對象:
isAdmin(): boolean {
this.getLoggedUser();
this.getRole();
console.log(this.admin);
console.log('isAdmin');
return this.admin;
}
getRole() {
this.httpClient.get<boolean>('/api/has-role-admin').
subscribe((data) => {
------------------------------------- This block will complete after the method returns
this.admin = data;
console.log(this.admin);
console.log('getRole');
}
);
}
如果您的代碼涉及可觀察對象,那么根據定義,它不能是順序的。 您需要重構您的方法,以便使用可觀察的方法,而不依賴於subscription方法中的副作用。
我將以這種方式重構您的代碼(我對您的代碼做出了一些假設,但是總體思路應該成立):
public interface UserInfo{
public isAdmin: boolean = false;
}
public getUserInfo(userId: integer): Observable<UserInfo> {
let params = new HttpParams()
.append('userId', userId.toString());
return this.http.get<UserInfo>(this.baseUrl + "api/has-role-admin", { params: params });
}
public isAdminUser(userId: number): Observable<boolean>(){
return this.getUserInfo(userId).pipe(map(x=> { return x.isAdmin; }));
}
並且服務器端api應該返回UserInfo
。 您可以調用isAdminUser(this.getLoggedUser().userId
。
這是在控制器中嗎? 名為isAdmin
的方法可能不應該進行HTTP調用,尤其是如果您的模板調用了該方法,因為這樣您最終將多次進行HTTP調用。
而是編寫一個ngOnInit
,在其中進行調用並將結果存儲到組件上的實例變量中。
同樣,HTTP調用會花費時間,並且您永遠都不應阻塞Javascript中的線程。 這樣,HTTP調用將生成您訂閱的Observable
。 訂閱會立即發生,但是直到HTTP響應到達時才會執行回調。
解決此問題的兩種常見模式是使用ngIf
隱藏該元素直到其被加載,或者使用async
管道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.