简体   繁体   中英

Angular Router.navigate to child route with queryParams

Can't navigate to child route with queryParams by Angular.Router.navigate

Аlready tried:

this.router.navigateByUrl('/desktop/search?q=folder'));

this.router.navigate(['desktop', 'search'], { queryParams: {q: 'folder'} });

this.router.navigate(['desktop/search'], { queryParams: {q: 'folder'} });

my routes:

{
    path: 'desktop',
    component: FavoritesPageComponent,
    children: [
      { path: 'desktop-admin', component: DesktopAdminComponent },
      { path: 'favorites', component: FavoritesBodyMainComponent },
      { path: 'sessions', component: SessionsComponent },
      { path: 'search', component: FavoritesBodySearchComponent },
      { path: 'shared_with_me', component: FavoritesBodySharedComponent },
      { path: 'recycle', component: FavoritesBodyRecycleComponent } 
    ] 
}

when i try to navigate to 'desktop/search?q=folder' i've got the following error:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'desktop/search%3Bq%3D%25D0%25BF%25D0%25B0%25D0%25BF%25D0%25BA%25D0%25B0'

What's wrong? Is there a way to use child routes with normal queryParams like

.../desktop/search?q=folder

this.route.queryParams.subscribe(params => {
   console.log('params['q']: ', params['q']);
});

router params in angular are separated by ';' not '&'. You must define route with parameter:

{ path: 'hero/:id', component: HeroDetailComponent }

then you can use this example for navigate:

this.router.navigate(['/heroes', { id: heroId }]);

As you can see router.navigate have one parameter and its object:

['/heroes', { id: heroId }]

Check this for more details

Look at this example:

1- Declaring route parameters:

// app.routing.ts    
export const routes: Routes = [
      { path: '', redirectTo: 'product-list', pathMatch: 'full' },
      { path: 'product-list', component: ProductList },
      { path: 'product-details/:id', component: ProductDetails }
    ];

to see the product details page for product with ID 10, you must use the following URL:

localhost:4200/product-details/10 // it's not this -> /product-details?id:10

2- Linking to routes with parameters:

<a [routerLink]="['/product-details', 10 or variable name]">
 title
</a>

or

<a (click)="goToProductDetails($event,10)">
     title
</a>

// into component.ts
goToProductDetails(e,id) {
  e.preventDefault();
  this.router.navigate(['/product-details', id]);
}

3- Reading route parameters:

// into component.ts

 constructor(private route: ActivatedRoute) {}

 ngOnInit() {
    this.route.params.subscribe(params => {
       this.id = +params['id']; 
    });
  }

I hope this helps you.

Sry, all works fine. It was my typo in code.. :) So, here is correct way to use queryParams:

this.router.navigate(['desktop', 'search'], { queryParams: {q: 'folder'} });

I don't wanna use UrlParams, because i will have a lot of params on this page and url like:

.../foo/bar/foo1/bar1/foo2/bar2/.../foo-x/bar-x

will not look beauty. Thnx all for help

Version: Angular: 14.1.0

Nothing above is working for me. Here is my answer.

Routes Config:

const routes: Routes = [
  { path: '', component: WelcomeComponent },
  { path: 'welcome', component: WelcomeComponent },
  {
    path: 'home', component: HomeComponent, canActivate: [AuthGuard],
    children: [{
      path: 'test1', component: Test1Component
    },
    {
      path: 'test2', component: Test2Component
    },
    {
      path: 'attendance', component: AttendanceComponent
    }]
  },
  { path: '**', component: WelcomeComponent }
];

Navigating to that route. Here we should be careful. In the above answers few people used navigateByUrl. navigateByUrl will not work in child routes.

The correct way of routing in child nodes is below

  navigate(path: string) {
    let cMName = this.cName + ": navigate. ";
    console.log(`In ${cMName} giving path: ${path}`);

    this.router.navigate([path], { relativeTo: this.activatedRoute, queryParams: { classCode: 'GRADE_1' } })

  }

Retrieving the query parm on the other end is as follows

    this.activatedRoute.paramMap.subscribe(params => {
      console.log(`In ${cMName}. In activated route block`);

      this.activatedRoute.queryParamMap.forEach(qParm => {
        if (qParm.has('classCode')) {
          let classCode = qParm.get('classCode');
          console.log(`${cMName} Selected Class Code: ${classCode}`);
          if (classCode != null)
            this.getStudentsFor(classCode);
          else
            console.log(`In ${cMName} empty class code recived`);
        }


      });
}

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