Angular2-router: How to only change a parameter of a route?

前端 未结 2 1347
情歌与酒
情歌与酒 2021-02-06 01:56

I want to have the following routes in my application:

export const routes: Routes = [
    { 
       path: \':universityId\', 
       component: UniversityCompon         


        
相关标签:
2条回答
  • 2021-02-06 02:40

    This is very simple. You can simply try to use this.router.navigate(["../2", "courses", "open"], {relativeTo: this.route});

    (or)

    this.router.navigate(["../2", "courses/open"], {relativeTo: this.route});

    This will redirect you to ../2/courses/open.

    0 讨论(0)
  • 2021-02-06 03:00

    Here is some code to go along with my comment above about using Tuples: So replicate this pattern twice... This shows how to integrate these classes into your project. So:

    1. change data-component-resolver.ts to parent-child-resolver.ts for code in the link.
    2. replace data-component.ts in the link with parent-child.component.ts below

    parent-child-resolver.ts

    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs';
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
    import {Parent} from '../shared/model/parent';
    import {Children} from '../shared/model/children';
    import {ParentService} from '../providers/parent.service';
    
    @Injectable()
    export class parentChildResolver implements Resolve<[Parent,(Children[])>
    
      constructor(private parentService : ParentService) {}
    
      resolve(  route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot
             ) : Observable<[Parent,(Children[])> 
      {
          return this.parentService.findParentById(route.params['id'])
            .switchMap(parent => 
                this.parentService.findChildrenForParent(parent.id),
                  (parent, children) => [parent, children]
             );
      }
    }
    

    parent-child.component.ts

    import {Component, OnInit} from '@angular/core';
    import {Parent} from '../shared/model/parent';
    import {Children} from '../shared/model/children';
    import {Observable} from 'rxjs';
    import {ActivatedRoute} from '@angular/router';
    
    @Component({
        selector: 'parent-child',
        templateUrl: './parent-child.component.html'
    })
    
    export class ParentChildComponent implements OnInit{
      $parent: Observable<Parent>;
      $children: Observable<Children[]>;
    
      constructor(private route:ActivatedRoute) {}
    
      ngOnInit() {
        this.parent$ = this.route.data.map(data => data['key'][0]); //from router.config.ts
        this.children$ = this.route.data.map(data => data['key'][1]);
      }
    }
    
    0 讨论(0)
提交回复
热议问题