BeniaminoBaggins
BeniaminoBaggins

Reputation: 12503

Return data from function with a subscription

getSchema(fileName): any {
    this.http.get(fileName)
        .map(this.extractData)
        .catch(this.handleError)
        .subscribe(data => {return data})
}

This function returns undefined. If using console.log instead of return, it logs the populated data. return stops it from awaiting the data response.

I'm trying things with an observer but it is looking like more code than necessary. What is the simplest way to get this code working (returning the data from the function)?

Upvotes: 1

Views: 7741

Answers (2)

penleychan
penleychan

Reputation: 5470

I agree with the others that you should check out the tutorial, and should subscribe in your component instead of inside your service.

However to answer your question, the reason why you are getting undefined is because you are missing return this.http.get(...); which should look like this.

getSchema(fileName): any {
    return this.http.get(fileName)
        .map(this.extractData)
        .catch(this.handleError)
        .subscribe(data => {return data})
}

Upvotes: 0

AVJT82
AVJT82

Reputation: 73387

I assume you want to subscribe somewhere in your component?

So this would be in your service: Here I assume that you do not send the filename as a parameter from the calling method, but you know the location of file in the service.

getSchema(): any { 
    return this.http.get(fileName) 
        .map(this.extractData)
        .catch(this.handleError)
}

And in your component you would subscribe:

this.myService.getSchema()
  .subscribe(data => {
    this.localVariable = data;
})

But yes, please check out e.g

HTTP-tutorial

In general, I think that all tutorials are really good for learning the basics :)

Upvotes: 1

Related Questions