【问题标题】:Return a response object from http get in Angular从 Angular 中的 http get 返回一个响应对象
【发布时间】:2020-12-24 10:52:56
【问题描述】:

我是 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;
  }

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

但是当我试图将它分配给一个局部变量并从 res 返回 responseObj 时。

但是 res 对象是未定义的。 有没有其他方法可以存档此功能

【问题讨论】:

标签: angular observable


【解决方案1】:

你没有得到任何响应的原因是所有的 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 不是很熟悉,一个更简单的方法是将请求转换为 Promise 并使用 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;
}

【讨论】:

    【解决方案2】:

    你应该像这样在订阅中移动你的控制台/返回语句:

    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 时它未定义的原因。

    【讨论】:

      【解决方案3】:

      理想情况下,您应该在 subscribe 方法中返回 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)
      )
      

      }

      【讨论】:

        猜你喜欢
        • 2017-12-04
        • 2022-07-20
        • 2017-04-05
        • 2015-12-13
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多