1
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)?

BeniaminoBaggins
  • 11,202
  • 41
  • 152
  • 287
  • You need to return the observable then subscribe to it wherever actually needs the result. Please find and read some ReactiveX tutorials. See http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call for the general problem you're facing. – jonrsharpe Jan 18 '17 at 21:26
  • See also the relevant section of the tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html – jonrsharpe Jan 18 '17 at 21:30

2 Answers2

1

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 :)

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167
0

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})
}
penleychan
  • 5,370
  • 1
  • 17
  • 28
  • I don't think this can be done. I was interested to see if it works, because I read just then that you cannot return from an asynchronous function. It returned something, but not anything relevant. It might be the http object or subscribe object – BeniaminoBaggins Jan 18 '17 at 23:28