angular - 服务调用另一个服务
问题描述
我正在尝试使用另一个服务 B(https://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);
}
我在组件中得到的数据是未定义的。提前致谢。
解决方案
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);
}
一些有用的资源:
推荐阅读
- android - 使用 google_mobile_ads 加载横幅时 Flutter App 崩溃
- python - 如何将python脚本连接到节点js?我想以异步方式从 python 读取数据和输出
- flask - Flask flask-login 需要创建一个抽象类和子类
- android - 导航参数双重错误:无法转义标识符“0.0”,因为它包含非法字符
- r - 需要在数据集上制作多个列联表
- c++ - 如何将 lua_tostring() 中的值分配给 utf-8 中 wstring 或 const wchar_t* 类型的变量
- delphi - 如何使用 Delphi 从 Windows 证书存储中读取 SSL 证书
- r - 如何在 R (Linux) 中增加内存大小使用
- python - 在 python 中使用 exec() 运行具有字典语法的字符串
- loopbackjs - 如何在包含在 mixin 中的模型上设置 Loopback 4 中的表名?