Home > Enterprise >  Angular Change Detection On Push
Angular Change Detection On Push

Time:05-27

I am trying to invoice change detection on the changing params page. After that, I get recipe JSON from DB. Why my code doesn't invoice component change detection when I create a new Subscription in the ngOnInit?

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription, switchMap } from 'rxjs';
import { RecipesApiService } from '../../../services/recipes/recipes-api.service';
import { IRecipeApi } from '../../../services/recipes/recipes';

@Component({
  selector: 'app-recipe-page',
  templateUrl: './recipe-page.component.html',
  styleUrls: ['./recipe-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RecipePageComponent implements OnInit, OnDestroy {
  recipe!: IRecipeApi;
  private sub$!: Subscription;

  constructor(
    private route: ActivatedRoute,
    private recipesApiService: RecipesApiService
  ) {}

  ngOnInit(): void {
    this.sub$ = this.route.params
      .pipe(
        switchMap((params) => {
          return this.recipesApiService.getRecipeApiById(params['id']);
        })
      )
      .subscribe((recipe) => {
        this.recipe = recipe;
      });
  }

  ngOnDestroy() {
    this.sub$.unsubscribe();
  }
}

CodePudding user response:

Why would it? With ChangeDetectionStrategy.OnPush you have to manually invoke change detection. That's the whole point of using it. In your code you don't do so, hence the change detection is not invoked.

Read more about change detection in the official docs here, or refer to one of the multiple tutorials available on the web.

  • Related