I want to get string value from Observable and return the value from the function to the caller function.
For eg: I have array of keys and would like to fetch the value (string) of all key one by one and display it html component which has menu bar.
Here are the ts files:
key-list.component.ts
public data = [ { 'key': 1, 'value' : this.getValue(1)},
{ 'key': 2, 'value' : this.getValue(2)},
...
];
private getValue(key: number): string {
return this.keyService.find(key).subscribe(response => {
return response;
});
}
keyService.ts
...
public find(key:number): Observable<any> {
return this.http.get(`/api/keys/${key}`).map(res => res.json() || {});
}
...
I want to display all the values in the html component. But getting error in key-list.component.ts that observable into type string.
How I can solve this subscription methodolgy and make sure that getValue should always return string, and make it flawless.
One of the solution is:
private getValue(key: number): string {
let result: string;
this.keyService.find(key).subscribe(res => result = res);
return result;
}
The above solution doesn't work always. What are the alternatives solution for this kind of problem?