【问题标题】:Angular 2 Router - named router-outlet navigation from codeAngular 2 Router - 从代码中命名的路由器出口导航
【发布时间】:2017-06-13 09:12:00
【问题描述】:

使用@angular/router": "3.4.7"。

建议的解决方案 here 不再有效。

      /**
        The ProductComponent depending on the url displays one of two info 
         components rendered in a named outlet called 'productOutlet'.
       */
        @Component({
          selector: 'product',
          template: 
          ` <router-outlet></router-outlet>
            <router-outlet name="productOutlet"></router-outlet>
          `
        })
        export class ProductComponent{
         }
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
          {
            path: 'product',
            component: ProductComponent,
            children: [
              {
                path: '',
                component: ProductOverviewComponent,
                outlet: 'productOutlet'},
              {
                path: 'details',
                component: ProductDetailsComponent,
                outlet: 'productOutlet' }
            ]
          }
      ]

    )],
  declarations: [
    ProductComponent,
    ProductHeaderComponent,
    ProductOverviewComponent,
    ProductDetailsComponent
  exports: [
    ProductComponent,
    ProductHeaderComponent,
    ProductOverviewComponent,
    ProductDetailsComponent
  ]
})
export class ProductModule {

}

手动导航按预期工作

http://localhost:5000/app/build/#/product-module/product(在命名插座中正确显示概览组件)

http://localhost:5000/app/build/#/product-module/product/(productOutlet:details)

(在命名插座中正确显示详细信息组件)

问题

无法找出执行编程导航的正确方法:

this.router.navigateByUrl('/(productOutlet:details)');

this.router.navigate(['', { outlets: { productOutlet: 'details' } }]);

出现以下错误:

错误:无法匹配任何路由。 URL 段:“详细信息”。

【问题讨论】:

    标签: angular2-routing router-outlet


    【解决方案1】:

    您可以像这样以编程方式导航

    this.router.navigate([{ outlets: { outletName: ['navigatingPath'] } }], { skipLocationChange: true });
    

    注意:skipLocationChange 用于隐藏地址栏中的 url。

    参考官方文档:https://angular.io/guide/router

    【讨论】:

    • 有人可以指出这个{ outlets: { outletName: ['navigatingPath'] } }语法的官方文档吗?这个解决方案对我有用,所以我在我的项目中使用它(并给了它一个赞成票),但我找不到它的正式文档,这既烦人又令人担忧。
    【解决方案2】:

    你可以试试相对导航

    this.router.navigate(['new'],{relativeTo:this.route})
    

    为此,您必须在组件中注入当前路由器快照和已激活路由

    import { Router,ActivatedRoute } from "@angular/router";
    
    constructor(private router:Router,private route:ActivatedRoute ){}
    

    【讨论】:

    • 不,仍然出现错误:无法匹配任何路线
    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 2018-04-16
    • 2017-02-05
    • 2018-08-06
    • 2022-11-03
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多