angularhttpngoninit

making HttpRequest in ngOnInit


I'm trying to make an httpRequest in ngOnInit, but for some reason it's not working. The if in my ngOnInit is working very well but the httpRequest it's not.

Here is my home.component.ts:

ngOnInit(){
  if (!this.token.possuiToken()) {
    this.router.navigate(['/', 'login']);
  }
  this.homeService.getStatus(this.status1)
}

And my home.service.ts:

public getStatus(status:any){
  const token = this.token.retornaToken();
  const headers = new HttpHeaders({ Authorization: `Bearer ${token}`,'Accept':'*/*','api-key':'E3AA97B8-7BEA-4E68-AA8D-55EA7A7E76F5'});

  return this.http.get(`${API}/obter-por-status/${status}`,{ headers, observe:'response' });
}

Solution

  • Your this.homeService.getStatus(this.status1) returns a Observable, it needs to be consumed to trigger.

    There is two ways of doing it in Angular.

    Option 1:

    this.homeService.getStatus(this.status1).subscribe(response => console.log(response))
    

    Option 2 (prefered way)

    myResponse$: Observable<MyResponseType>;
    this.myResponse$ = this.homeService.getStatus(this.status1);
    

    And consume your new observable in the template with async pipe like this:

    <div *ngIf="myResponse$ | async as myResponse">
    {{myResponse.data}}
    </div>
    

    I would highly recommend you to read thru this article to understand more about the different concepts: https://medium.com/angular-in-depth/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794