我正在尝试从API端点检索authConfig。在我的应用程序组件内部,我从服务请求功能。
this.userDetailService.getAuthConfig().then(config => {
this.oauthService.configure(config);
this.oauthService.initAuthorizationCodeFlow();
});
然后在我的服务中,设置auth配置并返回给应用程序组件。我在.then
上使用getAuthConfig
,因此当我需要它配置oauthService
时,配置对象就存在了。当我调试它时,我看到.configure
被一个空对象调用。为什么在getAuthConfig返回值之前要调用configure?
getEnvs(): Promise<any> {
return this.http.get('/backend').toPromise();
}
async getAuthConfig(): Promise<any> {
this.getEnvs().then((data) => {
const env = data.env;
const authConfig: AuthConfig = {
loginUrl: env.authorizationEndpoint,
redirectUri: env.redirectUris,
clientId: env.clientId,
scope: '',
oidc: false
};
return (authConfig);
});
}
答案 0 :(得分:2)
您需要从getAuthConfig
返回创建的承诺,以便getAuthConfig
的调用者可以正确地等待getAuthConfig
内生成的承诺链:
async getAuthConfig(): Promise<any> {
return this.getEnvs().then((data) => {
//^^^^^^
// ...
})
您将在与该类相同的类中的另一个异步方法中使用它:
async whatever() {
// this will now await for the promise chain
// within getAuthConfig and return the result
const authConfig = await this.getAuthConfig();
}
由于getAuthConfig
是一个异步函数,因此您可以选择利用它来清理它:
async getAuthConfig(): Promise<AuthConfig> {
const { env } = await this.getEnvs();
return {
loginUrl: env.authorizationEndpoint,
redirectUri: env.redirectUris,
clientId: env.clientId,
scope: '',
oidc: false
};
}