简体   繁体   English

从 Angular 中的 http get 返回响应对象

[英]Return a response object from http get in Angular

I'm new to angular and I've been trying to use http.get to get data from an API and assign it to a value in a component我是 angular 的新手,我一直在尝试使用 http.get 从 API 获取数据并将其分配给组件中的值

This is the method which is used to get data这是用于获取数据的方法

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

When I print the result inside the subscribe function I get the result当我在 subscribe 函数中打印结果时,我得到了结果

But when I've tried to assign it to a local variable and return responseObj from res.但是当我尝试将它分配给一个局部变量并从 res 返回 responseObj 时。

but the res object is undefined.但 res 对象未定义。 Is there any other way to archive this functionality有没有其他方法可以存档此功能

The reason you dont get any response is that all the HTTP method is async你没有得到任何响应的原因是所有的 HTTP 方法都是异步的

You have two options to handle the problem您有两种选择来处理问题

Use the observable provided by angular on itself使用 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)
    )
  }

and then you can use the res REplaySubject to subscribe in your component.然后您可以使用 res REplaySubject 订阅您的组件。

Or if you are not really familiar with RxJs and Observables/ReplaySubject a simpler method is to convert the request to a promise and use await或者,如果您不太熟悉 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;
}

You should move your console/return statement inside the subscribe like this:您应该像这样在订阅中移动控制台/返回语句:

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)

); );

Your function won't wait for the subscribe to complete because it's asynchronous.您的函数不会等待订阅完成,因为它是异步的。 That's why it's undefined when you try to access responseObj outside the subscribe.这就是为什么当您尝试在订阅之外访问 responseObj 时它是未定义的。

Ideally you should return res.responseObj within the subscribe method.理想情况下,您应该在 subscribe 方法中返回 res.responseObj 。 Or you can try -或者你可以试试——

 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)
)

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM