簡體   English   中英

如何在 Angular 中返回可觀察對象內的值

[英]How to return a value inside an observable in Angular

在 MSAL 進行身份驗證之前,我需要來自可觀察對象的響應來設置值。

有沒有辦法在 getAuthenticationConfiguration() observable 中返回值?

在可觀察對象中接收到值后,如何返回值。

ps 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 { }

我會嘗試 pipe 響應(未經測試的代碼):

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

我相信您的getAuthenticationConfiguration()應該看起來像這樣以從中返回一些響應:

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

當你訂閱它時,你可以這樣做:

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

所以基本上你可以在響應中為預期的屬性添加一個響應檢查,一旦收到然后只做進一步的代碼執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM