问题描述
我对角度可观测对象是陌生的.我有一个问题想要在订阅方法内返回一个值.我有以下方法(getFirebaseData(idForm:string):observable <any[]>
):
I'm new to observables in angular. I have a problem wanting to return a value inside a subscribe method. I havethe following method (getFirebaseData(idForm:string):observable <any[]>
):
getTotalQuestions(idForm:string){
let totalQuestions:number;
this.getFirebaseData(idForm+"/Metadatos")
.subscribe(items =>
{
items.map(item => {
totalQuestions=item.Total;
console.log(totalQuestions);
});
}
);
console.log(totalQuestions);
return totalQuestions;
}
第一个console.log(totalQuestions)
打印 4 ,第二个console.log(totalQuestions)
打印未定义.我知道订阅是异步操作,因此第二个console.log(totalQuestions)
(为了编写代码")打印时未定义,但是在订阅方法完成后,我找不到返回变量的方法.现在,如果我更改对地图的订阅:
the firts console.log(totalQuestions)
print 4 but the second console.log(totalQuestions)
print undefined. I understand that subscribe is an asynchronous operation and that for that reason the second console.log(totalQuestions)
("In order to write the code") print undefined, but I can not find the way to return the variable after the subscribe method has been completed. Now, if I change the subscribe to map:
getTotalQuestions(idForm:string){
let totalQuestions:number;
this.getFirebaseData(idForm+"/Metadatos")
.subscribe(items =>
{
items.map(item => {
totalQuestions=item.Total;
console.log(totalQuestions);
});
}
);
console.log(totalQuestions);
return totalQuestions;
}
第一个console.log(totalQuestions)
不打印任何内容,而第二个console.log(totalQuestions)
不打印任何内容.这是我不了解的,因为它会发生.
the firts console.log(totalQuestions)
does not print anything and the second console.log(totalQuestions)
print undefined. It's something that I do not understand because it happens.
希望您能帮助我阐明我不理解的概念.谢谢!
I hope you can help me clarify the concept that I do not understand. Thanks!
推荐答案
您不能像这样直接返回 totalQuestions ,您需要使用一个主题来实现.
You can't directly return totalQuestions like that, you need to use a subject to achieve that.
getTotalQuestions(idForm:string): Observable<string> {
let totalQuestions:number;
var subject = new Subject<string>();
this.getFirebaseData(idForm+"/Metadatos")
.subscribe(items => {
items.map(item => {
totalQuestions=item.Total;
console.log(totalQuestions);
subject.next(totalQuestions);
});
}
);
return subject.asObservable();
}
用法:getTotalQuestion(idForm).subscribe((r)=>console.log(r))
这篇关于如何在订阅Angular 4中返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!