如何在订阅 Angular 4 中返回值 [英] How to return value inside subscribe Angular 4

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

问题描述

我是角度观察的新手.我有一个问题,我想在 subscribe 方法中返回一个值.我有以下方法 (getFirebaseData(idForm:string):observable ):

I'm new to observables in angular. I have a problem where I want to return a value inside a subscribe method. I have the 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) 打印 undefined.我知道订阅是一个异步操作,因此第二个 console.log(totalQuestions)(为了编写代码")打印未定义,但我找不到返回的方法订阅方法完成后的变量.现在,如果我更改订阅地图:

the first console.log(totalQuestions) prints 4 but the second console.log(totalQuestions) prints undefined. I understand that subscribe is an asynchronous operation and for that reason the second console.log(totalQuestions) ("In order to write the code") prints 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 first console.log(totalQuestions) does not print anything and the second console.log(totalQuestions) prints undefined. It's something that I do not understand why 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 中返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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