0

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);

  • Can you be more specific? Your question seems to be not so clear! You'd like to get a string response from IsAuthorized api call? – Adam Sep 18 '19 at 18:57
  • @Adam Yes, I have the API, and only it knows the user is logged in or not. At the request, I get the username (if authorized) and "" (if not authorized). I want to send a request when a variable is received, but then I can not process the response without the `subscribe` method – Виталий Шебаниц Sep 18 '19 at 19:02
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Sep 18 '19 at 20:00

1 Answers1

2

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

Siddharth Pal
  • 1,408
  • 11
  • 23