[英]How to return a response from a request(post | get)?
There is a variable in the service that checks if the user is authorized: 服务中有一个变量,用于检查用户是否被授权:
get IsAuthorized():any{
return this.apiService.SendComand("GetFirstKassir");
}
SendCommand(within the usual post
request or get
): SendCommand(在通常的
post
请求或get
):
ApiService.SendComand(Command: string, Params?: any): Observable<any>
And I have to process the component as follows: 而且我必须按如下方式处理组件:
this.authorizeService.IsAuthorized.subscribe(
res => {
if (res.Name.length === 0) this.router.navigate(['/login'])
}
);
How do I make get IsAuthorized ()
returned string Name(not Observable<any>)
(which is inside the subscribe
. And the component I could write console.log(this.authorizeService.IsAuthorized);
我该如何使
get IsAuthorized ()
返回string Name(not Observable<any>)
(位于subscribe
内部。我可以编写该组件的console.log(this.authorizeService.IsAuthorized);
Here the thing you are handling is asynchrony. 在这里,您要处理的是异步。 So the IsAuthorized attribute can either be a promise/observable.
因此,IsAuthorized属性可以是一个Promise / Observable。 I believe all you are looking for is a simpler syntax.
我相信您正在寻找的只是一种更简单的语法。 So for that we can use async/await.
因此,我们可以使用异步/等待。
get IsAuthorized():any{
return this.apiService.SendComand("GetFirstKassir").toPromise();
}
and to use in the component lets say in ngOnInit we can use it as below: 要在组件中使用,可以在ngOnInit中说,我们可以如下使用它:
async ngOnInit() {
const isAuthorized = await this.authorizeService.IsAuthorized;
if(isAuthorized) { // works like normal boolean variable
}
}
Hope it helps!!! 希望能帮助到你!!! Cheers
干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.