Reputation: 1
I have a method which is returning a value and I'm assigning the return value to a variable. the function returns proper value but the variable is not set with the return value. But if I set this.size
inside the function I get proper value. I'm calling this.searchData
function from many functions, So I cannot do this(in this case I will have to use multi if
statements), So is there any way to get the return value from the function. I thought to use timeout
is there any other way around?
searchSize(event): void {
this.sizes = this.searchData(event, AppConsts.size);
}
searchData(event, property): any {
this._serviceProxy.getProperties(
property,
event.query,
event.query
).subscribe((result) => {
console.log(result.items);
return result.items;
});
}
Upvotes: 1
Views: 10798
Reputation: 276393
How to wait for return of a function in TypeScript?
return the observable
return this._serviceProxy.getProperties( // note : return
property,
event.query,
event.query
).subscribe((result) => {
console.log(result.items);
return result.items;
});
}
subscribe
to the returned value e.g.
searchData(something).subscribe
Upvotes: 0
Reputation: 250416
For cleaner simpler code, you could also use the async/await syntax. You have to convert your observable to a promise, and then you can await the result:
import * as rx from 'rxjs'
class ListResultDtoOfPropertyDTO{
items: any[]
}
class Test {
sizes: any[];
_serviceProxy : {
getProperties() : rx.Observable<ListResultDtoOfPropertyDTO>
}
async searchSize(event): Promise<void> {
this.sizes = await this.searchData(event);
}
async searchData(event): Promise<any[]> {
var result = await this._serviceProxy.getProperties()
.toPromise()
console.log(result.items);
return result.items;
}
}
Explanations:
Typescript allow a nicer syntax around waiting for results from a Promise. The syntax does not apply to Observables (hopefully in the future it will), we can however convert the Observable to a promise in this case. For more information about async/await syntax, have a look here
Upvotes: 2