Ionic-framework: ActivatedRoute is not updated correctly when using ion-router-outlet

Created on 4 Jan 2019  路  18Comments  路  Source: ionic-team/ionic-framework

Bug Report

Ionic version:
4.0.0-rc.0

Current behavior:
Getting correct activated route using Angular ActivatedRoute service only works the first time when "ion-router-outlet" is used and router NavigationEnd event occurs.

Expected behavior:
Getting correct activated route using Angular ActivatedRoute service works every time NavigationEnd event occurs and "ion-router-outlet" is used.

Steps to reproduce:
Try to get activated route every time Angular router fires NavigationEnd event.

Related code:
Following code correctly returns data object of the activated route when Angular "router-outlet" is used but only works the first time when Ionic "ion-router-outlet" is used:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';
import {filter, map, mergeMap} from 'rxjs/operators';

@Component({
    selector: 'app-foo',
    templateUrl: './foo.component.html',
    styleUrls: ['./foo.component.scss']
})
export class FooComponent implements OnInit {

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) {}

    ngOnInit() {
        this.router.events
            .pipe(
                filter((event) => event instanceof NavigationEnd),
                map(() => this.activatedRoute),
                map((route) => {
                    while (route.firstChild) {
                        route = route.firstChild;
                    }
                    return route;
                }),
                mergeMap((route) => route.data)
            )
            .subscribe(
                (routeData) => {
                    console.log(routeData);
                }
            );
    }

}

Other information:
daem0ndev explains the issue quite well in this comment.
This issue is quite important and it should be blocker for stable version 4 release.

As a workaround "IonicRouteStrategy" can be removed from app module providers until the issue is fixed.

Related issues:
ActivatedRoute.queryParams break after navigation
StackController Page reuse uses old Page data

Ionic info:

Ionic:

   ionic (Ionic CLI)             : 4.6.0
   Ionic Framework               : @ionic/angular 4.0.0-rc.0
   @angular-devkit/build-angular : 0.11.4
   @angular-devkit/schematics    : 7.1.4
   @angular/cli                  : 7.1.4
   @ionic/angular-toolkit        : 1.2.2

System:

   NodeJS : v10.1.0 (C:\Program Files\nodejs\node.exe)
   npm    : 6.5.0
   OS     : Windows 10
investigation angular

Most helpful comment

Same thing here, @abierbaum .
In our case, disabling { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } did the trick, but I think the problem deserves some deep investigation.

All 18 comments

Same here, after reloading the page ( cntrl + r ) this.ActivatedRoute.queryParams.subscribe is fired, but when I change queryparams nothing happens. If I load application on the main page for example my route is '/' and navigate to route with query params for example /category/:id?page=1, this.ActivatedRoute.queryParams.subscribe is working fine and I receive information when change query param page to 2.

import { Component, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ProductService } from '../../../providers/ProductService';
import { CategoryService } from '../../../providers/CategoryService';
import { map } from 'rxjs/operators';
import { IonInfiniteScroll } from '@ionic/angular';

@Component({
  selector: 'category-component',
  templateUrl: 'index.html',
  styleUrls: ['style.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class Category implements OnInit{


  sort: any;
  category: any;

  products = [];
  sortBy = '袩芯 锌芯写褉邪蟹斜懈褉邪薪械';
  loaded = false;
  limit = 20;
  page = 1;

  selectedFilters = {
    filters: [],
    promotion: false,
    stock: false
  };

  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;

  constructor(
    private ActivatedRoute: ActivatedRoute,
    private Router: Router,
    private ChangeDetectorRef: ChangeDetectorRef,
    private ProductService: ProductService,
    private CategoryService: CategoryService
  ) {

  }

  ngOnInit() {
    const { id } = this.ActivatedRoute.snapshot.params;

    if (id) {
      this.CategoryService.get(id).subscribe((res) => {
        this.category = res;
        this.ChangeDetectorRef.markForCheck();
      });
    }

    this.ActivatedRoute.queryParams.subscribe((params) => {

      console.log(params)

      const page = Number(params.page) - 1;

      this.sort = {
        'limit': this.limit,
        'skip': this.limit * page,
        'sortKey': 'created_at',
        'sort': -1,
        'match': { 'category_id': id }
      }

      this.onLoadProducts().subscribe();

    });
  }

  onLoadProducts() {
    return this.ProductService.getByCriteriaWithPriority(this.sort).pipe(map((res: any) => {

      res.forEach(element => {
        this.products.push(element);
      });

      if (res.length < this.limit) {
        this.loaded = true;
        this.infiniteScroll.disabled = true;;
      }

      this.infiniteScroll.complete();
      this.ChangeDetectorRef.markForCheck();

      return res;
    }));
  }

  loadData() {
    if (!this.loaded) {

      this.page++;

      this.Router.navigate(
        [],
        {
          relativeTo: this.ActivatedRoute,
          queryParams: { page: this.page },
          queryParamsHandling: "merge"
        });

    }
  }

  goBack() {
    this.page = 1;
    this.products = [];
    this.Router.navigate(
      [],
      {
        relativeTo: this.ActivatedRoute,
        queryParams: { page: this.page },
        queryParamsHandling: "merge"
      });
  }

}

This is still a problem in 4.0.1.

This is still a problem and is causing all of my relative navigation links to fail.

Same thing here, @abierbaum .
In our case, disabling { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } did the trick, but I think the problem deserves some deep investigation.

Hi there,

There is a PR up that should address several of the routing/caching issues we've been seeing: https://github.com/ionic-team/ionic/pull/17888

Would someone be able to try this PR out in one of their projects and provide some feedback on whether or not this resolves your issue?

Thanks!

Hey everyone. We just merged in #17888 which fixes this. Thanks for all your patience here 馃槃

@mhartington It's not fixed. Run the example code I provided to test with "IonicRouteStrategy" and "ion-tabs" layout.

Hi @hakimio,

Are you testing this with Ionic 4.2? If the issue is still happening, can you provide a repository with the code required to reproduce this issue?

Thanks!

@liamdebeasi Yes, 4.2. Code is provided above (first message). You just need to use it with IonicRouteStrategy and "ion-tabs".

Hi there,

Can you be more specific? Where do you intend the code you provided above to go? What steps do I need to take to reproduce this issue?

Thanks!

I have provided you the whole component class in the first post (same component used in multiple ionic tabs). Copy-paste the code and see if router NavigationEnd event is triggered when switching from one ionic tab to another and IonicRouteStrategy is used.
All the steps to reproduce are clearly described in the first post.

Hi there,

I am testing this on Ionic 4.2 and everything seems to be working correctly. Clicking on tab 2 shows the proper data for tab 2 and clicking back on tab 1 shows the proper data for tab 1.

I compared to Ionic 4.1 and clicking on tab 2 is showing data for tab 1.

Can you verify this on your end?

Thanks!

Can I simply email sample project to you?

Sure. You can attach a .zip here or shoot an email over to [email protected].

Thanks!

I've send you an email. Let me know if you can reproduce.

@liamdebeasi Did you manage to reproduce?

We still experiencing this issue after 4.2 update.

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.

Was this page helpful?
0 / 5 - 0 ratings