Roomy Roomy - 1 year ago 69
Javascript Question

How can I return the Http response?

I'm wondering if following thing is possible to do:

I need to return the response from http

request directly instead of returning

The example might clarify whole thing a bit:

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 Observable.create(observer => {
if (!ExampleService.model[uri]) {
let sub = this.http.get(uri).map(response => response.json()).subscribe(
src => observer.onNext(ExampleService.model[uri] = src),
err => console.error(err),
() => observer.onCompleted()
return () => sub.unsubscribe()

Answer Source

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.