Javascript angular 2 如何从订阅返回数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39295854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angular 2 how to return data from subscribe
提问by tsadkan yitbarek
This is What I Want To Do.
这就是我想要做的。
@Component({
selector: "data",
template: "<h1>{{ getData() }}</h1>"
})
export class DataComponent{
this.http.get(path).subscribe({
res => return res;
})
}
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?
如果getData
在内部调用DataComponent
,您可能建议将其分配给变量 likethis.data = res
并使用 i like {{data}}
。但我需要{{getData}}
为自己的目的使用 like 。请建议我?
回答by Günter Z?chbauer
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.
您也不能直接在类中使用此类代码。它需要移动到方法或构造函数中。
What you can do is not to subscribe()
directly but use an operator like map()
你能做的不是subscribe()
直接而是使用像这样的操作符map()
export class DataComponent{
someMethod() {
return this.http.get(path).map(res => {
return res.json();
});
}
}
In addition, you can combine multiple .map
with the same Observables as sometimes this improves code clarity and keeps things separate. Example:
此外,您可以将多个.map
与相同的 Observable组合在一起,因为有时这会提高代码清晰度并保持独立。例子:
validateResponse = (response) => validate(response);
parseJson = (json) => JSON.parse(json);
fetchUnits() {
return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}
This way an observable will be return the caller can subscribe to
这样一个 observable 将返回调用者可以订阅的
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
and
和
res => return res.json()
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.
是箭头函数。它们类似于正常功能。当数据从响应到达时,这些函数被传递给可观察对象subscribe(...)
或map(...)
从可观察对象调用。这就是为什么不能直接返回数据的原因,因为someMethod()
完成时,数据还没有收到。
回答by qwerty_igor
Two ways I know of:
我知道的两种方式:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
一旦返回信息,就像在承诺中一样,这会将您的结果分配给局部变量。然后你就做{{ localVar }}
Another Way is to get a observable as a localVariable.
另一种方法是将 observable 作为 localVariable。
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
这样你就暴露了一个 observable,此时你可以在你的 html 中使用 AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
请尝试一下,让我知道它是否有效。此外,由于 angular 2 很新,如果有什么问题,请随时发表评论。
Hope it helps
希望能帮助到你
回答by sajal rajabhoj
I have used this way lots time ...
我已经用这种方式很多次了......
@Component({
selector: "data",
template: "<h1>{{ getData() }}</h1>"
})
export class DataComponent{
this.http.get(path).subscribe({
DataComponent.setSubscribeData(res);
})
}
static subscribeData:any;
static setSubscribeData(data):any{
DataComponent.subscribeData=data;
return data;
}
use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...
使用静态关键字并节省您的时间...在这里您可以使用静态变量或直接返回您想要的对象....希望它会帮助您...快乐编码...