0

I have a service which is calling two method. And service method I am calling in my component, it returning me undefined.

my service

checkPermission(permissionName: string): boolean {
    const pageLevelCompanySettingName = "Security_Permission_Check_View";

    let permission: boolean;
    this.checkCompanySettingForPermission(
      pageLevelCompanySettingName
    ).subscribe(res => {
      if (res.SysConfig.Value === "true") {
        this.hasPermission(permissionName).subscribe(data => {
          permission = data.permission;
        });
      }

    });
    return permission;
  }

my component

const abc =  this.permission.checkPermission(pageLevelCompanySettingName);
    console.log('final', abc);

2 Answers2

0

If you are waiting for an http response from an API, then something in your code may need to be awaited. You can try async/await - this may resolve why your "abc" boolean is returning undefined.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function.

Dan G
  • 51
  • 8
0

You have to do asynchronous method which you calling, that means you have to wait until the second method return response. So have to use the observable in angular (rxjs)


//method 1
    checkPermission(permissionName: string): Observable<boolean> {
       const pageLevelCompanySettingName = "Security_Permission_Check_View";

       let permission$ = new Subject<boolean>();
       this.checkCompanySettingForPermission(pageLevelCompanySettingName).subscribe(res => {
         if (res.SysConfig.Value === "true") {
           this.hasPermission(permissionName).subscribe(data => {
             permission$.next(data.permission);
           });
         }
       });
     return permission$.asObservable();
    }

//method 2 
    checkPermission(permissionName: string): Observable<boolean> {
       const pageLevelCompanySettingName = "Security_Permission_Check_View"; 
    
     return this.checkCompanySettingForPermission(pageLevelCompanySettingName).pipe(
      mergeMap(res => {
        return (res.SysConfig.Value === "true") ? 
             this.hasPermission(permissionName) : of(false)
      })
    );
 }

And you have to subscribe to the service method in your component

this.permission.checkPermission(pageLevelCompanySettingName).subscribe(
(value) => {
   console.log('final', value);
});

And always do the unsubscribe the method where you subscribed in the component

Yaseer
  • 506
  • 2
  • 14