-1

I want to get the status code and body of a subscription.

WOWEE I cant. Well I can but utterly useless since I cant return.

@Injectable()
export class ApiService {

constructor(private _http: HttpClient, 
              private _authHttp: HttpClient,
              public jwtHelper: JwtHelperService,
              private loggedinService: LoggedinService){

  }

  status_code:number

 def test(){
    var result_ = this._http.get(this.getEndpointUrl(endpoint), {headers: new HttpHeaders({ 'Content-Type':  'application/json','Authorization': localStorage.getItem('id_token') }),observe: 'response'});

    result_.subscribe(resp=>{
      this.status_code = resp.status
      console.log(resp.status). //works
    })

    let wtf = result_.toPromise().then(resp => console.log('toPromise', this.status_code = resp.status));

   return this.status_code.  //null

 }

How do I wait to return? Clearly returning before the subscribe finishes

Liam
  • 27,717
  • 28
  • 128
  • 190
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Mar 26 '20 at 08:54
  • 1
    You should really read the docs on this more thoroughly https://angular.io/guide/http – Liam Mar 26 '20 at 08:56

1 Answers1

2

Subscription is done asynchronously that's why when you return value of this.status_code synchronously it's not set.

What you can do is returning

this._http.get(this.getEndpointUrl(endpoint), {headers: new HttpHeaders({ 'Content-Type':  'application/json','Authorization': localStorage.getItem('id_token') }),observe: 'response'})

in your method and subscribe to that it in a place where the method is invoked.

Stefan
  • 1,431
  • 2
  • 17
  • 33