Home > database >  How to return a value inside an observable in Angular
How to return a value inside an observable in Angular

Time:02-23

I need a response from an observable to set values before the MSAL authenticates.

Is there a way to return value inside the getAuthenticationConfiguration() observable?

How can I return values after the values are received inside the observable.

p.s. It is not possible to return inside the subscribe function.

export function MSALInstanceFactory(service: AzureService): IPublicClientApplication {
    service.getIdentityManagerApiRestService().getAuthenticationConfiguration().subscribe(response => {
        return new PublicClientApplication({
            auth: response.authenticationConfiguration, <-------- I want this
            cache: {
                cacheLocation: BrowserCacheLocation.LocalStorage,
                storeAuthStateInCookie: isIE, // set to true for IE 11. Remove this line to use Angular Universal
            }
        });
    })
}


@NgModule({
    declarations: [
        AzureComponent
    ],
    exports: [
        AzureComponent
    ],
    providers: [
        {
            provide: MSAL_INSTANCE,
            useFactory: MSALInstanceFactory,
            deps: [AzureService]
        }
    ]
})

export class AzureModule { }

CodePudding user response:

I would try to pipe the response (untested code):

service
  .getIdentityManagerApiRestService()
  .getAuthenticationConfiguration()
  .pipe(switchMap((res) => res.authenticationConfiguration))
  .subscribe((config) => {
    return new PublicClientApplication({
      auth: config,
      cache: {
        cacheLocation: BrowserCacheLocation.LocalStorage,
        storeAuthStateInCookie: isIE, // set to true for IE 11. Remove this line to use Angular Universal
      },
    });
  });

CodePudding user response:

I believe your getAuthenticationConfiguration() should look like this to return some response from it:

getAuthenticationConfiguration() {
  return authenticationConfiguration$.pipe(map(data) => data.authenticationConfiguration))
}

and when you subscribe to it, you can do this:

service
.getIdentityManagerApiRestService()
.getAuthenticationConfiguration()
.subscribe(response => {
    if(response.authenticationConfiguration) {
        return new PublicClientApplication({
            auth: response.authenticationConfiguration,
            cache: {
                cacheLocation: BrowserCacheLocation.LocalStorage,
                storeAuthStateInCookie: isIE,
            }
        });
    }
})

So basically you can add a check on response for the expected property in the response, once received then only do further code execution.

  • Related