【问题标题】:Angular, extract the value from a promiseAngular,从承诺中提取价值
【发布时间】:2020-10-25 14:04:51
【问题描述】:

我有一个返回 Promise 的函数,在这个 Promise 中我得到了一个解析对象。 这是我的服务的功能很好。

buscarUsuario(email: string){
return new Promise((resolve, reject) => {
  this.http.post(`${URL}/user/email`, {email})
           .subscribe(resp => {                     
           //console.log(resp['usuario']);
           
           resolve(resp['usuario']);
          }); 
}) 

}

然后我从这个var中的promise中得到值:

const getDatos = this.usuarioService.buscarUsuario(this.correoUsuario.value.toString());

然后我调用 var 从解析中获取值,但我无法从那里提取该值:

var usuario: Usuario;
getDatos.then(usu => {
 
      usuario = usu;
      //Here I can see the value
      console.log(usuario);
      
    });
//But here I can't see the value
//And it's where I really need to get the value
console.log(usuario);

那么,我如何在 Promise 之外获得该值?

【问题讨论】:

标签: node.js angular typescript http post


【解决方案1】:

不推荐在 Angular 中使用 Promises。 Angular 推荐使用Observable 来处理异步操作

让我们尝试更改您的代码以仅返回 Observables

buscarUsuario = (email: string)  =>
  this.http.post<any>(`${URL}/user/email`, {email}).pipe(
    map(resp => resp.usuario as Usuario)
  )

基本上,上面的代码返回一个Observable&lt;any&gt;(任何类型的可观察)。我使用&lt;any&gt; 进行类型转换,将结果转换为Obserable&lt;any&gt;。接下来我使用管道从响应中提取usuario

现在我们可以将这个值赋给一个变量...

const getDatos$ = this.usuarioService.buscarUsuario(this.correoUsuario.value.toString());

注意:这是Observable,您需要订阅它

Observable 可以像任何其他属性一样被赋值

const usuario: Observable<Usuario> = getDatos$

【讨论】:

    【解决方案2】:

    您无法在该函数之外获取值,原因是因为您使用了 Promise,因此您需要等到 Promise 返回该值,因此最好的方法是您在 Promise.then 中完成其余功能。

    getDatos.then(usu => {
      //implement your other functionality
    });`
    
      
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多