Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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]);
  }
}

大佬总结

以上是大佬教程为你收集整理的Angular2-router:如何只更改路由的参数?全部内容,希望文章能够帮你解决Angular2-router:如何只更改路由的参数?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。