首页 > 解决方案 > 如何为从 Angular 中的 API 后端收集的提供者设置值

问题描述

如何从 API 在这里设置值?

在此处输入图像描述

标签: angularangular-servicesangular-moduleangular-providers

解决方案


理想情况下,您可以通过提供程序中的异步工厂来实现这一点。不幸的是,这一直是一个悬而未决的问题

一种解决方法可能是创建一个包装服务,该服务第一次加载 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电话,因此并不理想,但这是一种解决方法。

如果您有任何其他依赖项需要注入到服务中,您也可以将它们注入到您的包装服务中。

工作演示:https ://stackblitz.com/edit/angular-wlbyqp


推荐阅读