Reputation: 11
I am trying to build a Service A using another Service B (https://angular.io/tutorial/toh-pt4) as following:
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);
}
}
}
and a component calls the map defined above as:
ngOnInit(){
this.getTestMap();
}
getTestMap(): void {
this.serviceA.getTestMap().subscribe(data => this.componentMap = data);
}
The data I got in the component is undefined. Thanks in advance.
Upvotes: 1
Views: 75
Reputation: 391
I beleive the getTestMap method should be like:
getTestMap(): Observable<Map<string, string>> {
return this.serviceB.getSomething(new HttpParams()).(data => {
this.testMap.set('A', data);
return data;
}
}
Upvotes: 0
Reputation: 144
getTestMap()
from ServiceA should return an Observable
. In your example you don't return anything. It could look like that (provided this.serviceB.getSomething()
also returns an 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)
);
}
}
And in your component:
ngOnInit(){
this.getTestMap();
}
getTestMap(): void {
this.serviceA.getTestMap().subscribe(data => this.componentMap = data);
}
Some useful resources:
Upvotes: 2