angular 2如何从订阅返回数据 [英] angular 2 how to return data from subscribe

查看:154
本文介绍了angular 2如何从订阅返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的事。

@Component({
   selector: "data",
   template: "<h1>{{ getData() }}</h1>"
})

export class DataComponent{
    this.http.get(path).subscribe({
       res => return res;
    })
}

如果在 DataComponent 中调用 getData ,您可以建议将其分配给变量喜欢 this.data = res 并使用我喜欢 {{data}} 。但是我需要使用像 {{getData}} 为了我自己的目的。请建议我吗?

If getData was called inside the DataComponent, You may suggest assign it to a variable like this.data = res and use i like {{data}}.But I needed to use like {{getData}} for my own purpose.Please suggest me?

推荐答案

您无法直接返回该值,因为它是异步调用。
异步调用意味着它在后台运行(实际安排在以后执行),同时代码继续执行。

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

你也不能这样直接在类中的代码。它需要移动到方法或构造函数中。

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

你可以做的不是 subscribe()直接但使用像 map()

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

此外,您可以合并多个 .map 使用相同的Observable,有时可以提高代码清晰度并保持分离。示例:

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

这样一个observable将返回调用者可以订阅

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

来电者也可以在另一个班级。这只是为了简洁。

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

res => return res.json()

是箭头函数。它们与普通功能类似。这些函数传递给 subscribe(...) map(...)从observable调用当数据从响应中到达时。
这就是无法直接返回数据的原因,因为当 someMethod()完成时,尚未收到数据。

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

这篇关于angular 2如何从订阅返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆