【问题标题】:Service calling another service服务调用另一个服务
【发布时间】:2020-02-05 16:02:53
【问题描述】:

我正在尝试使用另一个 Service B (https://angular.io/tutorial/toh-pt4) 构建一个 Service 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);

}

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

【问题讨论】:

  • 在组件中,getTestMap(): void { this.serviceB.getTestMap() ...是这个问题的错字吗?换句话说,组件应该/是调用this.serviceA.getTestMap()吗?
  • 是的,这是一个错字。我已经纠正了。谢谢!

标签: angular


【解决方案1】:

来自 ServiceA 的getTestMap() 应该返回一个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);
}

一些有用的资源:

【讨论】:

  • 谢谢,@madder。是的,ServiceB 也返回一个 Observable。我测试为: ngOnInit(){ this.getTestMap(); console.log(this.componentMap);我已经检查了资源,但我仍然无法使其工作。也没有提供解决方案。谢谢。
  • 有效!谢谢!! (我不熟悉生命周期钩子并且打印在错误的地方)
【解决方案2】:

我相信 getTestMap 方法应该是这样的:

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

【讨论】:

  • 错过了从方法中观察到的返回。更新了它。它现在可以工作了。
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 2011-01-31
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多