Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']);
});
like image 262
Valentyn Chernysh Avatar asked Mar 25 '19 08:03

Valentyn Chernysh


1 Answers

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.

like image 140
Morteza Ebrahimi Avatar answered Sep 27 '22 20:09

Morteza Ebrahimi