等待 http.get() 的响应

Wait response for http.get()

我正在尝试使用 angular 和 ionic 2 创建登录功能。此功能将验证用户是否通过 php 服务器和 return 用户 id.But http.get() 以异步形式工作,所以我无法比较用户是否存在于数据库中,因为函数的 return 未定义。我尝试了两种方法,使用 observable 和 promises:

With observable, function that calls the service:

login() 
  {
    this.usuario = this.loginservice.get_usuario(this.loginusuario).subscribe(response =>this.usuario = response);
    console.log(this.usuario);
  }

Service code:

public get_usuario(usuario):Observable<any>
  {
      return this.http.get(this.urlusuario +"/"+ usuario.usuario +"/"+ 
   usuario.senha); 
  }

这样,我第一次点击触发login()函数的按钮时,得到的响应是undefined值。第二次点击,return是上次请求的值

Using promise, function that calls the service:

login() 
  {
    this.usuario = this.loginservice.get_usuario(this.loginusuario);
    console.log(this.usuario);
  }

service code:

public get_usuario(usuario):Promise<any>
  {
    var resultado;
      return this.http.get(this.urlusuario +"/"+ usuario.usuario +"/"+ usuario.senha).toPromise().then(function(data){
         return  data; 
      });
  }

使用 promise 我在第一次执行登录函数时得到了 id return,但是我找不到任何方法来访问 __zone_symbol__value,根据console.log() console response

我想知道是否有办法等待 http.get () 响应继续程序执行(在使用 observable 的情况下)或者我如何访问对象 return来自承诺

$http.get 函数 returns Promise,因为 .get() 方法发送异步 ajax 请求。要对您的变量写入响应,您需要这样做:

login () {
    var self = this;
    this.http.get('/url/').then(response => {
        self.usuario = response;
        // It will write response from server to your variable when the 
        // request will be done
    }).catch(error => /*Your error handler*/);
}

在您调用服务的代码中,您需要订阅您的可观察对象,并在订阅内调用之后执行您想要发生的任何事情。

这里也不要设置this.usuario = this.loginservice.get_usuario...。您将 this.usario 设置为等于 Observable,而不是 Observable 的响应。

login() 
{
  this.loginservice.get_usuario(this.loginusuario).subscribe(response => {
    this.usuario = response;
    console.log(this.usuario);
  });
}

That way, the first time I click the button that triggers the login () function, I get the undefined value in response. The second time I click, it returns the value of the previous request.

发生这种情况是因为您 console.log 没有等待订阅完成。第二次点击,是returns上一次请求的值,因为同理,不是等待订阅完成,因为console.log不在订阅中,而是等到你第二次点击它,第一个请求确实完成了。因此,this.loginusuario 是在第一个 console.log.

之后设置的

在函数中使用 async 并在调用承诺中使用 await

async login() 
  {
    await this.usuario = this.loginservice.get_usuario(this.loginusuario);
    console.log(this.usuario);
  }