[英]How to return a response from a request(post | get)?
服務中有一個變量,用於檢查用戶是否被授權:
get IsAuthorized():any{
return this.apiService.SendComand("GetFirstKassir");
}
SendCommand(在通常的post
請求或get
):
ApiService.SendComand(Command: string, Params?: any): Observable<any>
而且我必須按如下方式處理組件:
this.authorizeService.IsAuthorized.subscribe(
res => {
if (res.Name.length === 0) this.router.navigate(['/login'])
}
);
我該如何使get IsAuthorized ()
返回string Name(not Observable<any>)
(位於subscribe
內部。我可以編寫該組件的console.log(this.authorizeService.IsAuthorized);
在這里,您要處理的是異步。 因此,IsAuthorized屬性可以是一個Promise / Observable。 我相信您正在尋找的只是一種更簡單的語法。 因此,我們可以使用異步/等待。
get IsAuthorized():any{
return this.apiService.SendComand("GetFirstKassir").toPromise();
}
要在組件中使用,可以在ngOnInit中說,我們可以如下使用它:
async ngOnInit() {
const isAuthorized = await this.authorizeService.IsAuthorized;
if(isAuthorized) { // works like normal boolean variable
}
}
希望能幫助到你!!! 干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.