Reputation: 2564
I'm wondering if following thing is possible to do:
I need to return the response from http GET
request directly instead of returning Observable<Response>
instance.
The example might clarify whole thing a bit:
@Injectable()
export class ExampleService {
constructor( @Inject(Http) protected http: Http) { }
static model: { [uri: string]: any } = {}
public get(uri: string): any {
if (typeof ExampleService.model[uri] === 'undefined') {
ExampleService.model[uri] = this.http.get(uri).map(response => response.json()) // additionally do some magic here, it is Observable<any> instance now
}
return ExampleService.model[uri]
}
}
Summary: according to Günter Zöchbauer answer above solution is not possible, instead of that I need to use something like this:
public get(uri: string): Observable<any> {
return new Observable(observer => {
if (!ExampleService.model[uri]) {
let sub = this.http.get(uri).map(response => response.json()).subscribe(
src => observer.next(ExampleService.model[uri] = src),
err => console.error(err),
() => observer.complete()
)
return () => sub.unsubscribe()
}
observer.next(ExampleService.model[uri])
observer.complete()
})
}
Upvotes: 1
Views: 479
Reputation: 657118
This is not possible because the HTTP request is async and the get()
method returns before the call to the server is even made. Instead when the response from the server arrives the callback passed to subscribe(...)
is called.
There is no way to go back from async to sync execution.
You can only return the observable for the caller to subscribe to it and do something when the response arrives.
Upvotes: 5