如何在不重构的情况下处理Angular 2+(7)路由更改?

时间:2019-03-20 16:00:37

标签: angular angular7

现在,推荐的路由是使用一个看起来像这样的路由数组:

const appRoutes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: 'page1', component: Page1Component },  // can't use RouterStringService here I don't think...
    { path: 'page2', component: Page2Component }
]
@NgModule({...})
export class AppRouting Module {}

这一切都很好。我们可以使用它来导航:

  • ts个文件-router.navigate(['/page1'])
  • html文件-[routerLink]="/page1"

很酷。这很好。但是,如果我们需要将page1更改为home-feed(或者不是page1的任何内容)会发生什么?重构字符串文字是一个皮塔饼,并提出问题(尤其是在html中)。我们可以这样使用重定向:

// changes to above code block
{ path: 'page1', redirectTo: 'new-page1' },
{ path: 'new-page1', component NewPage1Component },

但这只会增加记住重定向的精神开销,因为其他代码引用仍然可能是router.navigate(['/page1'])

我们还可以使用几乎导入到所有地方的服务。这(除非我弄错了)在appRoutes中不可用,因为它是在模块外部声明的? (这在第一个代码块中已记录)

export class RouterStringService {
    static page1: string = '/page1'
    static page2: string = '/page2

    // put string builders here too for things like /pageX/:id

    constructor() {}
}

你们如何处理?我知道重构不是理想的,但是有时候必须要进行重构。我最担心的是缺少路由,因为angular 7使用字符串文字推送。您是使用e2e测试来捕获这一问题还是可以通过编程方式对其进行修复?

1 个答案:

答案 0 :(得分:3)

由于您提到的原因,我还旨在尽可能避免代码中的字符串文字。一个好主意是拥有配置文件(例如,就像environment.ts一样),用作不同url-s的参考字典。

如果您需要更改确切的字符串文字,则可以在一处进行。

可以从TS文件或HTML模板中引用这些配置对象,如果您将其导出到相应组件的模板中。

例如: urls.ts文件在资产或其他任何文件夹中的某个位置:

export const AppUrls = {
    base: "...",
    login: "...",
    ...
} 

在ts文件中

   import {AppUrls} from '..../urls.ts';

    const appRoutes: Routes = [
        { path: '', redirectTo: AppUrls.login, pathMatch: 'full' },

在模板中,首先将其导出:

import {AppUrls} from '..../urls.ts';

@Component({
  selector: '...
})
export class SomeComponent implements OnInit {

  AppUrls = AppUrls;

和html中的

[routerLink]="{{AppUrls.login}}"

此外,router.navigate(['/page1'])不需要斜杠,您可以将不同的URL分隔为数组条目:router.navigate(['firstpart', 'secondpart'])->这将带您进入/firstpart/secondpart