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?
You are trying to return
Observable
from functiongetValue
, andreturn response
orreturn result
won't work because request forhttp.get
is asynchronous.Here are some options what you can do:
Option1: using Async Pipe at your template to subscribe for result of
http.get
and remove subscribe part from functiongetValue
.Option2: Define the array
data
withoutvalue
field and update its value field later. But be careful that thevalue
field will beundefined
unless you get response fromthis.keyService.find(key)
.Hope this will help.
UPDATE from OP
With some slight changes in the above option1 it worked like charm.
Here are the changes:
Thanks for reminding to use Async Pipe @Pengyy (From OP)