简体   繁体   中英

Angular ActivateRoute will activate change detection

I notice that angular ActivatedRoute will activate change detection immediately, which will cause ExpressionChangedAfterItHasBeenCheckedError error. How could I avoid it?

  public ngOnInit(): void {
    this.subscriptions.push(this.pageService.pageChanges.subscribe(() => {
      this.currentPage = this.pageService.currentPageData();
    }));
    this.route.params
      .switchMap(params => {
        console.log("route.params.switchMap called: ", params);
        const requestedPageNumber = parseInt(params['page'], 10);
        return this.wizard.getPage(requestedPageNumber);
      })
      .subscribe((refocus) => {
        console.log("route.params subscribed called: ", refocus);
        this.refocus = !!refocus;
      });
    this.subscriptions.push(this.pageService.saveChanges.subscribe(() => {
      if (this.page) {
        this.page.saveData();
      }
    }));
  }

enter image description here

Although It isn't a clean solution, I recommend a setTimeout() . This do an asyncronous-like execution on lifecycle hook.

Example:

setTimeout(() => {
 this.route.params
  .switchMap(params => {
    console.log("route.params.switchMap called: ", params);
    const requestedPageNumber = parseInt(params['page'], 10);
    return this.wizard.getPage(requestedPageNumber);
  })
  .subscribe((refocus) => {
    console.log("route.params subscribed called: ", refocus);
    this.refocus = !!refocus;
  });
  this.subscriptions.push(this.pageService.saveChanges.subscribe(() => {
    if (this.page) {
      this.page.saveData();
    }
  }));
), 1000};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM