簡體   English   中英

Angular2 Routing:redirectTo動態生成的字符串

[英]Angular2 Routing: redirectTo a dynamically generated string

默認情況下,我需要重定向到今天的日期。 這是我現在的路由配置:

import { CALENDAR_ROUTE } from './_methods/utils';

export const appRoutes: Routes = [
   {
    path: CalendarComponent.path, 
    component: CalendarComponent,
    canActivate: [AuthGuard],
    resolve: refDataResolver,
    data: {
      navi: {
        at: 'main',
        icon: 'navbar-calendar'
      },
      roles: {
        employeeOnly: true
      }
    },
    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: CALENDAR_ROUTE.DEFAULT_MONTH
      },
      {
        path: LAYOUT_MONTH,
        children: [
          {
            path: '',
            pathMatch: 'full',
            redirectTo: CALENDAR_ROUTE.MONTH
          },
          {
            path: ':year/:month',
            component: CalendarMonthViewComponent
          },
        ]
      },
      {
        path: LAYOUT_DAY,
        children: [
          {
            path: '',
            pathMatch: 'full',
            redirectTo: CALENDAR_ROUTE.DAY
          },
          {
            path: ':year/:month/:day',
            component: CalendarDayViewComponent
          },
        ]
      }
    ]
    }
  ];

這是我在utils.ts中生成字符串的方法

import { LAYOUT_MONTH } from './../_classes/const';
import * as moment from 'moment';

export function getRoute(withDay: boolean, prefix?: string): string {
    const now = moment();
    const day = ( withDay ) ? now.format('DD') : null;
    return [prefix, now.format('YYYY'), now.format('MM'), day]
        .filter( str => !!str)
        .join('/');
}

export const CALENDAR_ROUTE = {
    DEFAULT_MONTH: getRoute(false, LAYOUT_MONTH),
    MONTH: getRoute(false),
    DAY: getRoute(true)
};

這一切順利 - 在開發模式和localhost - 直到我需要為UAT / PROD編譯它,它利用AOT構建,然后拋出一個

ERROR in Error during template compile of 'AppRoutingModule' 
Function calls are not supported in decorators but 'getRoute' was called in 'appRoutes' 
'appRoutes' calls 'getRoute' at app/app-routing.module.ts(67,42).

我還沒有找到解決這個問題的方法。 有一些問題會使用providersuseValue - 但在這里感覺就像是一種過度useValue 也許有一種不同的解決方法? 也許我應該以不同的方式構建組件? 有任何想法嗎?

一種解決方案可能是將Router注入組件,然后在運行時更新路由配置。

我自己沒有測試過,但想法是這樣的:

在您的組件中

constructor(private router: Router) {
   this.router.config.unshift({path: '', component: '', redirectTo: 'Your new redirect path'})
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM