Return 来自 http 的响应对象进入 Angular

Return a response object from http get in Angular

我是 angular 的新手,我一直在尝试使用 http.get 从 API 获取数据并将其分配给组件中的值

这是用来获取数据的方法

  public getByUserName(username:String):User{

     let res:CommonResponse;

     this.http.get<CommonResponse>(BASE_URL+'/'+username)
    .subscribe(  (response) => { res = response },
      error => this.errorHandler.handleError(error)
    )
    console.log("Response "+ res)
    return res.responseObj;
  }

当我在订阅函数中打印结果时,我得到了结果

但是当我试图将它分配给局部变量和 return 来自 res.

的 responseObj 时

但是 res 对象未定义。 是否有任何其他方式来存档此功能

您应该像这样在订阅中移动您的 console/return 语句:

public getByUserName(username:String):User{
this.http.get<CommonResponse>(BASE_URL+'/'+username).subscribe(  (response) => {
  console.log("Response "+ res);
  return res.responseObj;
},
error => this.errorHandler.handleError(error)

);

您的函数不会等待订阅完成,因为它是异步的。这就是当您尝试在订阅之外访问 responseObj 时未定义的原因。

您没有收到任何响应的原因是所有 HTTP 方法都是异步的

你有两种选择来处理这个问题

在自身上使用 angular 提供的 observable

let res:ReplaySubject<CommonResponse>=new ReplaySubject(); 

public getByUserName(username:String):User{    
    this.http.get<CommonResponse>(BASE_URL+'/'+username)
    .subscribe(  (response) => { this.res.next(response) },
      error => this.errorHandler.handleError(error)
    )
  }

然后你可以在你的组件中使用res REplaySubject来订阅。

或者如果你不是很熟悉 RxJs 和 Observables/ReplaySubject 一个更简单的方法是将请求转换为承诺并使用 await

public async getByUserName(username:String):User{
     let res:CommonResponse;    
     res= await this.http.get<CommonResponse>(BASE_URL+'/'+username).toPromise()
          .catch((error)=>{
              this.errorHandler.handleError(error)
                 })
      console.log("Response "+ res)
      return res.responseObj;
}

理想情况下,您应该 return res.responseObj 在订阅方法中。 或者你可以试试 -

 public getByUserName(username:String):User{

 let res:CommonResponse;

 return this.http.get<CommonResponse>(BASE_URL+'/'+username)
.subscribe(  (response) => { res = response.responseObj },
  error => this.errorHandler.handleError(error)
)

}