如何在 redirectTo 字段中提供 Dynamic url?

How to give a Dynamic url in the redirectTo field?

输入错误url (404) 我想重定向之前的url!!所以我必须在 "RedirectTo" 归档的

中给出前一页 url

App.module.ts

const appRoutes: Routes = [
{path: 'Sk', canActivate: [AuthGuard], children: [ { path: 'announce', 
component: AnnounceComponent },{ path: '**', redirectTo: ?, pathMatch: 'full' }]},{ path: '**',component: AppComponent}];

首先将路由导入到要更改 redirectTo 的组件。 然后你可以在你的组件中访问路由并更改 redirectTo 值。

app.routing.ts :

export let routes: Routes = [
    { path: '', redirectTo: 'pages', pathMatch: 'full' },
    { path: 'pages', loadChildren: 'app/pages/pages.module#PagesModule' },
    { path: 'login', loadChildren: 'app/pages/login/login.module#LoginModule' },
    { path: '**', component: ErrorComponent }
];

exampleComponent.ts :

// importing routes
import { routes } from '../app.routing';

// i'm changing it in ngOnInit for example.
ngOnInit() {

 routes[0].redirectTo = 'login';

}

如果输入 url 错误则重定向到上一页 :

  1. 创建一个新组件,比如errorComponent。每当 url 出错时,我们就使用这个组件。所以在你的路线中做如下
    export let routes: Routes = [
       { path: '**', component: ErrorComponent }
    ];
  1. 在errorComponent中我们会写回到上一页的逻辑。
    import { Location } from '@angular/common';

    ngOnInit() {
      this.location.back();
    }