【问题标题】:How to config routing Angular4 router如何配置路由Angular4路由器
【发布时间】:2018-02-28 11:32:06
【问题描述】:

问题:我正在为我的应用程序配置路由。我想让我的 url 像 https://localhost:4200/hero=id 一样,其中 id 将是用户从 Heroscomponent 中选择的内容。这对我不起作用。

如果我尝试下面的 url,其路径是 /hero/:id,根据 angular 文档,它在音素上起作用。

https://localhost:4200/hero/:id

有人能帮我解决这个问题吗?

这是我的路由配置文件

 const appRoutes: Routes = [
  { path: 'hero', component: HeroesComponent },
  {path: 'hero{=:id}', component: HeroDetailComponent},
  {
    path: 'home',
    redirectTo: '/hero',
    data: { title: 'Heroes List' }
  },{
    path: 'student',
    component: AppTable
  },{
    path: 'video',
    component: VideoTagComponent
  },{ path: '',
    redirectTo: '/hero',
    pathMatch: 'full'
  }
  // { path: '**', component: PageNotFoundComponent }
];

下面是我要路由到 path = "/hero="+id

的 HeroesComponent 文件
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import {Hero} from './hero';


const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

@Component({
    selector: 'my-heroes',
    templateUrl: './heroes.html',
    styleUrls: ['./app.component.css']
})

export class HeroesComponent {
    hero = HEROES;
    path:string;
    selectedHero: Hero;

    constructor(private router: Router){}        

    onSelect(hero: Hero): void {
      this.selectedHero = hero;
      this.path = "/hero=" +this.selectedHero.id.toString();
      this.router.navigate([this.path]);
    }

    // gotoDetail(): void {
    // }
}

这是我在浏览器控制台中遇到的错误。
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'hero%3D13' Error: Cannot match any routes. URL Segment: 'hero%3D13'**strong text**

【问题讨论】:

  • id 路由使用“=”是一个要求吗?
  • 是的@JayDeeEss 这是一个要求。

标签: javascript angular typescript angular4-router


【解决方案1】:

我找到了解决这个问题的方法。

因为 Angular 不支持这个.. 所以,我们可以创建一个 CustomUrlSerializer

   import { UrlSerializer, UrlTree, DefaultUrlSerializer } from '@angular/router';

export class CustomUrlSerializer implements UrlSerializer {
    public parse(url: any): UrlTree {
        let _serializer = new DefaultUrlSerializer();
        return _serializer.parse(url.replace('=', '%3D'));
    }

    public serialize(tree: UrlTree): any {     
        let _serializer = new DefaultUrlSerializer();
        let path = _serializer.serialize(tree);
        // use regex to replace as per the requirement.
        return path.replace(/%3D/g, '=');
    }
}

在您引导 AppComponent 的位置导入此模块

import { CustomUrlSerializer } from 'file path';

@NgModule({
  bootstrap: [ AppComponent ],
  imports: [
  ],
  providers: [
    { provide: UrlSerializer, useClass: CustomUrlSerializer},

  ]
})

在你的路由模块中创建一个匹配器来映射路由。

export const ROUTES: Routes = [
  { matcher: pathMatcher, component: ComponetName},
  ];

const KEYWORD = /hero=([^?]*)/;


export function pathMatcher(url: UrlSegment[], group: UrlSegmentGroup, route: Route): any {
    if (url.length >= 1) {
        const [part1] = url
        if (part1.path.startsWith('hero')) {
            const [,keyword] = KEYWORD.exec(part1.path) || ['',''];
            let consumedUrl: UrlSegment[] = [];
            consumedUrl.push(url[0]);
            return {
                consumed: consumedUrl,
                posParams: { //The parameters if any you want to pass to ur component
                    heroId: new UrlSegment(keyword,{})
                }
            }
        }
    }
    return null
}

现在,在您的组件中,您可以使用

获取 heroId
this.route.params.subscribe((params)=>{
          this.data = params['heroId'];
      })

其中路由是ActivatedRoute的实例

【讨论】:

    【解决方案2】:

    而不是{path: 'hero{=:id}', component: HeroDetailComponent},
    使用{path: 'hero/:id', component: HeroDetailComponent},
    {path: 'hero/:id/detail', component: HeroDetailComponent},

    根据angular documentation:您应该以这种方式创建路径: { path: 'hero/:id', component: HeroDetailComponent },

    在您的 HeroDetailComponent 中,您将能够以这种方式访问​​ id:

    constructor(
      private route: ActivatedRoute,
      private router: Router,
      private service: HeroService
    ) {}
    
    ngOnInit() {
      const hero = this.route.paramMap
        .switchMap((params: ParamMap) =>
          this.service.getHero(params.get('id')));
    } 
    

    更多详情official Documentation

    【讨论】:

    • @meorfi 感谢您的帮助。我知道您指的是角度文档。但是,我需要配置像 {path: 'hero{=:id}', component: HeroDetailComponent}, 这样的路由
    • @harsh,不确定路由是否允许路径中的特殊字符。您应该使用 queryParams 来设置 id=1key=a&value=b 或其他任何东西,但您会破坏最佳实践。在此处查看查询与路径参数之间的差异:stackoverflow.com/a/31261026/896258
    • @meorfi 我知道每个人都应该遵循最佳实践。可能是我们做错了,问题是我们正在从 angular 1.x 迁移到 4。因此,无法更改我们应用程序的当前 SEO url。我尝试对路径进行硬编码,如“/hero=13”,它可以工作。但是,如果我动态创建 url,它就无法以某种方式工作。我还尝试覆盖路由器 acc 的路由器 UrlSerializer。到这个stackoverflow.com/questions/39541185/…,但这并没有覆盖 DefaultUrlSerializer。
    猜你喜欢
    • 1970-01-01
    • 2017-12-07
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多