Angular2-router:如何只更改路由的参数?

前端之家收集整理的这篇文章主要介绍了Angular2-router:如何只更改路由的参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望在我的应用程序中有以下路由:
export const routes: Routes = [
    { 
       path: ':universityId',component: UniversityComponent,children: [
           { path: 'info',component: UniversityInfoComponent },{ path: 'courses/:status',component: CoursesByStatusComponent }
       ]
    }
]

在/ 1 / info或/ 1 / courses / open url上,如何更改:universityId仅来自UniversityComponent?

简单的router.navigate([‘../’,2],{relativeTo:currentRoute})不会这样做,因为它重定向到/ 2,丢失所有其他信息.使用’./2/courses/open也不是一个选项 – 那时我可以在任何子路线上.
我能想到的最好的是:

const urlTree = this.router.parseUrl(this.router.url);
urlTree.root.children['primary'].segments[0].path = '2';
this.router.navigateByUrl(urlTree);

但它有点难看

这里有一些代码与我上面关于使用元组的评论一起:所以复制这个模式两次……这 shows如何将这些类集成到你的项目中.
所以:

>将data-component-resolver.ts更改为parent-child-resolver.ts以获取链接中的代码.
>使用下面的parent-child.component.ts替换链接中的data-component.ts

亲子-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]
         );
  }
}

家长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]);
  }
}

猜你在找的Angularjs相关文章