javascript - 如何配置Angular4路由器的路由

标签 javascript angular typescript angular4-router

问题:我正在为我的应用程序配置路由。我想让我的网址像 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 }
];

下面是我的 HeroesComponent 文件,我正在其中路由到 path = "/hero="+id

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**

最佳答案

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

因为 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的实例

关于javascript - 如何配置Angular4路由器的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46304533/

相关文章:

Javascript 添加动态输入字段

Angular 5 - HttpClient Post 不发布

angular - 如何通过本地git将Angular 4应用程序部署到azure web应用程序

javascript - Angular 中嵌套订阅的错误

javascript - Angular2 - 登录后重定向

javascript - Fullcalendar 显示每天的事件数

javascript - 当 Controller 返回时,从 javascript 在新选项卡中打开 View

javascript - 使复选框像单选按钮一样可以取消选中

javascript - 找不到 'source-map' 的类型定义文件

javascript - Excel标签中显示未定义