首页 > 解决方案 > 服务调用另一个服务

问题描述

我正在尝试使用另一个服务 Bhttps://angular.io/tutorial/toh-pt4 )构建服务 A,如下所示:

export class ServiceA {       
   private testMap: Map<string, string> = new Map();

   constructor(private serviceB: ServiceB) {}

   getTestMap(): Observable<Map<string, string>> {
      this.serviceB.getSomething(new HttpParams()).(data => {
         this.testMap.set('A', data);
      }
   }
}

并且一个组件将上面定义的地图称为:

ngOnInit(){
   this.getTestMap();
}

getTestMap(): void {
   this.serviceA.getTestMap().subscribe(data => this.componentMap = data);

}

我在组件中得到的数据是未定义的。提前致谢。

标签: angular

解决方案


getTestMap()从 ServiceA 应该返回一个Observable. 在您的示例中,您不返回任何内容。它可能看起来像这样(假设this.serviceB.getSomething()还返回一个Observable):

export class ServiceA {       
   private testMap: Map<string, string> = new Map();

   constructor(private serviceB: ServiceB) {}

   getTestMap(): Observable<Map<string, string>> {
      return this.serviceB.getSomething(new HttpParams())
        .pipe(
          tap(data => this.testMap.set('A', data)),
          map(() => this.testMap)
        );
   }
}

在你的组件中:

ngOnInit(){
   this.getTestMap();
}

getTestMap(): void {
   this.serviceA.getTestMap().subscribe(data => this.componentMap = data);
}

一些有用的资源:


推荐阅读