angular 2如何从订阅返回数据

这就是我想做的。


@Component({

   selector: "data",

   template: "<h1>{{ getData() }}</h1>"

})


export class DataComponent{

    this.http.get(path).subscribe({

       res => return res;

    })

}

如果getData在中被调用DataComponent,您可能会建议将其分配给变量like this.data = res并使用i like {{data}}。但是{{getData}}出于个人目的,我需要使用like 。请提出建议?


炎炎设计
浏览 961回答 3
3回答

江户川乱折腾

您只是不能直接返回该值,因为它是一个异步调用。异步调用意味着在代码继续执行的同时,它正在后台运行(实际上已安排在以后执行)。您也不能直接在类中有这样的代码。需要将其移至方法或构造函数中。您可以做的不是subscribe()直接使用而是使用像map()export class DataComponent{&nbsp; &nbsp; someMethod() {&nbsp; &nbsp; &nbsp; return this.http.get(path).map(res => {&nbsp; &nbsp; &nbsp; &nbsp; return res.json();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}另外,您可以将多个对象.map与相同的Observables 结合使用,因为有时这可以提高代码的清晰度,并使事情分开。例:validateResponse = (response) => validate(response);parseJson = (json) => JSON.parse(json);fetchUnits() {&nbsp; &nbsp; return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);}这样,观察者将返回,呼叫者可以订阅export class DataComponent{&nbsp; &nbsp; someMethod() {&nbsp; &nbsp; &nbsp; return this.http.get(path).map(res => {&nbsp; &nbsp; &nbsp; &nbsp; return res.json();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; otherMethod() {&nbsp; &nbsp; &nbsp; this.someMethod().subscribe(data => this.data = data);&nbsp; &nbsp; }}呼叫者也可以在另一个班级。这里只是为了简洁。data => this.data = data和res => return res.json()是箭头功能。它们类似于正常功能。当数据从响应到达时,这些函数将传递到可观察对象subscribe(...)或map(...)从可观察对象调用。这就是为什么不能直接返回数据的原因,因为someMethod()完成后还没有收到数据。
打开App,查看更多内容
随时随地看视频慕课网APP