首页 > 解决方案 > 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?

标签: angular

解决方案


您可以使用 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;

是的,现在你有一个变量中的令牌:)


推荐阅读