Angular - 路由器配置 - redirectTo使用参数/变量段

时间:2017-06-28 15:33:53

标签: angular router

在下面的示例路由配置中,我收到错误:无法重定向到'/ ip /:id'。输入localhost时找不到':id':8080 \ sso \ ip \ 1。我试图了解如何使用路径的可变段重定向。在这种情况下:似乎无法找到id。我引用了https://vsavkin.com/angular-router-understanding-redirects-2826177761fc,它描述了一个类似的用例,其中在redirectTo属性中使用动态段。

使用启动的/ sso / ip / :id 路由中的:id参数来解析id吗?提出了类似的问题,但从未回复:https://groups.google.com/forum/#!topic/angular/Mw0N3qYphO8

非常感谢任何帮助?

const appRoutes: Routes = [
  { 
      path: 'ip',
      children: [
        {
          path: ':id',
          children: [
            {
              path: 'tcv',
              component: IpTcvComponent          
            },
            {
              path: '',
              component: IpComponent          
            }
          ]
        },
        {
          path: '',
          component: IpHomeComponent          
        }
      ]
  },  
  { 
    path: 'sso',
    children: [
      {
        path: 'ip',
        children: [
          {
            path: ':id',
            children: [
              {
                path: 'tcv',
                pathMatch: 'full',
                redirectTo: '/ip/:id/tcv'
              },
              {
                path: '',
                pathMatch: 'full',
                redirectTo: '/ip/:id'
              }
            ]
          },
          {
            path: '',
            pathMatch: 'full',
            redirectTo: '/ip'
          }
        ]
      }
    ]
  }
];

1 个答案:

答案 0 :(得分:0)

我的方法是手动处理重定向,如果我不能让路由配置工作。使用RedirectService方法redirectInFlight()监听Router.events可观察对象。当路由器尝试转到目标路径(例如/sso/ip/:id)时,透明地重定向到正确的路径:/ip/:id

然后我会将服务添加到AppModule.providers,在AppComponent中注入服务,然后致电redirectInFlight()

<强> AppComponent

@Component({
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {

    //inject the RedirectService
    constructor(private redirectSvc:RedirectService){}

    //start listening to the router and redirecting
    ngOnInit() {this.redirectSvc.redirectInFlight();}
}

<强> RedirectService

import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import 'rxjs/Rx'; //replace with just the classes you need from RxJS library

@Injectable()
export class RedirectService {
    events$:Observable<any>; //stream of Router events

    constructor(private router:Router) {
        this.events$ =
            //listen to router events and inspect the `url` string property
            //and filter for urls that begin with /sso
            this.router.events.filter(e=> e.url && e.url.startsWith('/sso'))
    }

    redirectInFlight(){
        //First remove /sso from the start of url to fix it
        this.events$.map(e => e.url.replace('/sso',''))
            //navigate to the fixed URL
            .subscribe(newUrl=>this.router.navigateByUrl(newUrl));
    }
}

最后,您可以从路由器配置中删除整个sso路径及其子路径,从而简化了它。

Live demo

注意:此实现是一个起点。您可以通过存储和引用重定向地图,而不是硬编码&#34; / sso&#34;来使其更加强大。