Home > Blockchain >  Is it correct way to return from method with subscription inside (Angular)
Is it correct way to return from method with subscription inside (Angular)

Time:05-11

Is it correct way to return value like in method below?

  private canView(permission: string, resource: string): boolean {
    let result: boolean;

    this.accessChecker.isGranted(permission, resource)
      .pipe(
        take(1)
      )
      .subscribe(
        granted => {
          result = granted;
        }
      );

    return result;
  }

Can I have a situation when result returned before it value will be set in the subscription (for as i know subcribe is asynchronous)? If yes what is the correct way?

CodePudding user response:

are you using this to create boolean for different canView permissions? If so you can just turn those booleans into Observables.

canViewElement1$ = this.canView('element1', 'res1');
canViewElement2$ = this.canView('element2', 'res2');

private canView(permission: string, resource: string): Observable<boolean> {
    return this.accessChecker.isGranted(permission, resource);
}

on the template, if you use it for ngIf, call it with async pipe. you won't have to worry about unsubscribing or take(1) this way:

<div *ngIf="canViewElement1$ | async">
...
</div>

CodePudding user response:

Result might not have the value from the subscription in that point of time

CodePudding user response:

You may want to make canView as an async function, convert the Observable returned by isGranted to promise using toPromise(), then await for the result

  private async canView(permission: string, resource: string): boolean {
    let result: boolean = await this.accessChecker.isGranted(permission, resource)
      .pipe(
        take(1)
      ).toPromise();
    return result;
  }
  • Related