Reputation: 612
The function getEventId()
is returning this.eventId
.
If this.eventId == null
,
a function that makes an http request is being called.
this.eventId = resp
(the respons from the request).
ngOnInit() { // the function bellow makes http request. this.getCustomerFileByCode().subscribe(data => { // get Id from server this.eventId = data[0]; }) }
getEventId() { if (this.eventId) { //if the server request returned already response return of(this.eventId) } else { getCustomerFileByCode().subscrive(data =>{ this.eventId = data[0] }) // wait some how to the server response and return the value return this.eventId; }) } }
getCustomerFileByCode(): Observable { return this.http.post(this._url, JSON.stringify(params), this.options) }
How do I return the value from the http request in the function getEventId()
?
Upvotes: 0
Views: 1480
Reputation: 58039
I think that you want do some like
getEventId(elementId):Observable<any> {
if (this.eventId) { //if the server request returned already
return of(this.eventId)
} else {
return this.getCustomerFileByCode(elementId).pipe(
map(data=>data[0]),
tap(res => {
this.eventId = res;
})
}
And in ngOnInit
this.getEventId(this.elementId).subscribe(()=> {
...make something more...
...don't worry about this.eventId because the "tap" ...
...on the observable yet store the value...
})
See that the getEventId return an observable, if "this.eventId" is yet, simply return of, else call to the API, transform the response -using map- and store the value -using tap-. Of course, as all observables you need subscribe to "launch". Well, you can equal teh value in subscribe and don't use "tap". But in general the observables must be declared in a service and subscribe in component, so it's more logical that the variable "belong" to the service.
Upvotes: 1