angular - 如何为从 Angular 中的 API 后端收集的提供者设置值
解决方案
理想情况下,您可以通过提供程序中的异步工厂来实现这一点。不幸的是,这一直是一个悬而未决的问题。
一种解决方法可能是创建一个包装服务,该服务第一次加载 api 密钥,然后从主题重播加载的服务。
@Injectable({ providedIn: 'root'})
export class ServiceWrapper {
private service$: Subject<Service>;
getService(): Observable<Service> {
if (this.service$) {
return this.service$.pipe(
take(1)
);
}
this.service$ = new ReplaySubject<Service>(1);
this.http.get(apiKeyUrl).subscribe(apiKey => {
this.service$.next(new Service(apiKey));
});
return this.service$.pipe(
take(1)
);
}
}
然后,您可以将此包装服务注入组件(或任何使用它的组件):
export class MyComponent {
constructor(private service: ServiceWrapper) {}
ngOnInit(): void {
this.service.getService().pipe(
switchMap(service => service.method())
).subscribe(result => {
// do something
});
}
}
您最终会接到很多switchMap
电话,因此并不理想,但这是一种解决方法。
如果您有任何其他依赖项需要注入到服务中,您也可以将它们注入到您的包装服务中。
推荐阅读
- javascript - 如何通过JavaScript用逗号替换数组中的点
- testing - 为条件编译定义自定义属性的正确方法是什么?
- reactjs - 将 Ant 设计表导出为 pdf 格式
- cuda - windows下运行nvprof --metrics命令报错:cuda profiling error
- java - Hyperledger Fabric:如何实时查看 Java 链码的调试输出?
- javascript - javascript变量分配json url
- php - 如何从 Google Cloud Datastore 中查找在 PHP 中具有数值键的实体?
- google-sheets - 基于 Google 表格中的两个日期的条件格式难题
- css - 显示 textField 错误消息时,Material UI 按钮向下移动
- typescript - 如何修复中继单元测试抛出错误“不变违规:graphql:运行时意外调用”?