Home > Back-end >  Http Observable and subscribe in Constructor
Http Observable and subscribe in Constructor

Time:10-02

Can we use http observable and subscribe method in the constructor. What are the advantages and disadvantage of that ? How the Angular Lifecycle work if we put rxjs code in constructor

CodePudding user response:

ngOnInit gets run after your @Input() variables get set. So the disadvantage to subscribing to an observable in your constructor is that your component inputs might not be set when an observable fires an event.

CodePudding user response:

I would recommend subscribing to the observable in the html with an async pipe. This will keep you from accidentally getting memory leaks from not unsubscribing.

@Component({
  template: `
    <div *ngIf="api$ | async as result">
      <h1>{{ result.title }}</h1>
      <div>{{ result.descr }}</div>

      <button (click)="next(result.next)">Next Page</button>
    </div>
  `
})
export class ExampleComponent {
  private api = new BehaviorSubject<string>('/page1');
  api$ = this.api.pipe(
    exhaustMap(url => this.http.get(url))
  );

  constructor(
    private readonly http: HttpClient
  ) { }

  next(url: string) {
    this.api.next(url);
  }
}

Here is some example api data:

{
  "title": "Hello World",
  "descr": "This is the welcome page!",
  "next": "/page2"
}
  • Related