Return 来自订阅函数的数据

Return data from function with a subscription

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

此函数return未定义。如果使用 console.log 而不是 return,它会记录填充的数据。 return 停止等待数据响应。

我正在与观察者一起尝试,但看起来代码比必要的多。让这段代码工作的最简单方法是什么(return从函数中获取数据)?

我假设您想订阅组件中的某处?

所以这将为您服务: 在这里,我假设您没有将 filename 作为调用方法的参数发送,但您知道文件在服务中的位置。

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

在您的组件中,您将订阅:

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

但是是的,请查看例如

HTTP-tutorial

总的来说,我认为所有教程都非常适合学习基础知识:)

我同意其他人的意见,您应该查看教程,并且应该在您的组件中而不是在您的服务中订阅。

但是要回答你的问题,你得到未定义的原因是因为你缺少 return this.http.get(...);,它应该看起来像这样。

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