angular - Is there a way to store data returned from an observable into a property of a service that can be called by multiple services synchronously?
问题描述
Here's what I want.
Instead of storing token to local storage, I would like to store it into a service, but since getting the token involves getting it from an observable
I only get 'undefined'
returned, unless the service returns observable
and then have to subscribe again in every other service that has the first service injected.
Is there a way to avoid this and get the token synchronously from the service?
解决方案
您可以使用 aAPP_INITIALIZER
来获取在应用程序初始化时运行的令牌(无论您从哪里获得)。这是一个简化的示例:
@Injectable()
export class MyStartupService {
constructor(...) { }
get token() {
return this.token;
}
load() {
// return observable or promise, e.g if a http request
return this.http.get<any>('url').pipe(
map((data:any) => this.token = data)
)
}
}
在您的 app.module 中标记此服务:
export function startupServiceFactory(provider: MyStartupService) {
return (data) => provider.load();
}
并在应用程序模块提供程序数组中:
MyStartupService,
{
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [MyStartupService], // add more dependencies, for example HttpClient
multi: true
},
只需在您想要的地方注入启动服务,然后调用并存储您的令牌......
constructor(private startup: MyStartupService) { }
// ...
this.token = this.startup.token;
是的,现在你有一个变量中的令牌:)
推荐阅读
- python - 得到[Errno 54]连接由python中的对等方重置
- vue.js - 在路由我的网站页面时如何保存页面的数据?(Vue 路由器)
- docker - Docker Compose 和 Xdebug 在 PhpStorm 中不起作用
- rust - 如何迭代切片的所有可能分区(非空子切片)?
- json - 如何在颤动中使用动态变化的键解析json数据?
- pouchdb - 如何通过 PouchDB 同步请求传递标头?
- amazon-web-services - Nginx 为 RESTapi 端点调用返回 index.html 页面
- ssh - 在使用调试模块时对主机执行 Ansible ssh
- azure - 在 copyIndex 中排除资源部署
- html - 全背景渐变覆盖,无重复