【发布时间】:2021-02-15 06:10:17
【问题描述】:
我正在尝试弄清楚如何在 Angular 11 中使用 useFactory 作为异步函数。现在我有这个:
import { ApolloClientOptions } from 'apollo-client';
import { FirebaseService } from './firebase.service';
// other imports here...
export async function createApollo(httpLink: HttpLink, fs: FirebaseService): Promise<ApolloClientOptions<any>> {
const token = await fs.getToken();
const getHeaders = async () => {
return {
"X-Auth-Token": token,
};
};
// functions has more content here...
return Promise.resolve({
link: errorLink.concat(link),
cache: new InMemoryCache(),
});
}
@NgModule({
imports: [HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, FirebaseService],
},
],
})
export class DgraphModule { }
问题是它解决了异步函数,但不是在返回它之前。我在 StackOverFlow 上看到了一些其他帖子来解决这个问题,但他们最终忽略了函数的 async 部分。你不能有一个不在异步函数中的等待,所以我在这里没有注意到。
如果该函数不是异步函数,您也不能将异步函数放在异步函数中......那我该怎么办?
更新:2/11/21 - 根据this 的说法,PlatformBrowserDynamic() 可以做到这一点,但我不明白如何在我的模块中实现它。 p>
更新:21 年 2 月 13 日 这是指向 codeandbox.io 的链接 - 忽略缺少 html 或工作端点,但您可以查看模块并将其更改为 async 函数查看是否存在 Invariant Violation 错误。 ---> 确保查看代码和沙盒控制台是否有错误。
【问题讨论】:
-
这个函数返回一个promise,所以在实现中你应该返回一个promise。然后,您可以在该承诺中包含您的逻辑,该逻辑应在最后解决该承诺。所以类似 return new Promise(async function (resolve) { #some stuff here you await then call resolve("answer"'); })
-
我刚刚返回了一个已解决的 Promise,我收到了相同的错误
Invariant Violation: To initialize Apollo Client, you must specify a 'cache' property in the options object.,因为它返回的是承诺而不是值。一切都可以在没有异步的情况下工作,但是我需要异步才能使我的令牌标头工作...查看更新的完整代码... -
我对 apollo 客户端不是很熟悉。您希望如何使用提供程序 APOLLO_OPTIONS?它应该只是一个 POJO js 对象吗?
-
在这种情况下,它只是 Apollo 的选项(可以是任何东西,但我使用导入更新了代码),但关键是如何将 async 与 @ 一起使用987654327@.
标签: angular async-await angular-module angular-providers angular11