Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading