首页 > 解决方案 > 打字稿:在 Observable 之外获取数据

问题描述

我试图在 Typescript 中发送一个 HttpRequest。我需要将收到的数据存储在订阅功能之外。但是当我想在订阅之外打印用户变量时,它是undefined. 在订阅功能中它工作正常。那么我如何才能访问订阅功能之外的数据呢?

private user: User;

public sendHttpLogin(username: string, password: string) {

  this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
    //save the data on a User Object
    this.user = data;
    //this works fine
    console.log(this.user)
  });

  //this is undefined
  console.log(this.user);
}

标签: angularjstypescriptobservablehttprequestsubscribe

解决方案


第二个在返回console.log之前被调用http.get,所以这就是它未定义的原因。

您的第一个console.log是正确的,您只能使用从get函数返回的数据。

您可以在那里调用另一个函数来继续您的应用程序的流程。

private user: User;

public sendHttpLogin(username: string, password: string) {

  this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
    this.continueApp(data)
  })
}

private continueApp(data){
    this.user = data
}

推荐阅读