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 orget):

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 thesubscribe. And the component I could write console.log(this.authorizeService.IsAuthorized);

Answer

Here the thing you are handling is asynchrony. So the IsAuthorized attribute can either be a 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:

  async ngOnInit() {
    const isAuthorized = await this.authorizeService.IsAuthorized;
    if(isAuthorized) { // works like normal boolean variable
    }
  }

Hope it helps!!! Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *