简体   繁体   English

Angular2命名路由

[英]Angular2 named routes

I use Angular2 Webpack Starter in this newest version and in file ./src/app/app.routes.ts I add 'my-new-route' and i want to name it as: "my.route" 我在最新版本和文件中使用Angular2 Webpack Starter ./src/app/app.routes.ts我添加'my-new-route',我想将其命名为:“my.route”

export const routes: RouterConfig = [
  { path: '',      component: Home },
  { path: 'home',  component: Home },
  // make sure you match the component type string to the require in asyncRoutes
  { path: 'about', component: 'About' },
  { path: 'my-new-route', component: 'Dashboard', name:"my.route" },
  { path: '**',    component: NoContent },
];

but there is a problem - it not working! 但是有一个问题 - 它不起作用! TypeScript writes: (name) "... is not assignable to type Route[]". TypeScript写道:(名称)“...不能分配给类型Route []”。 I check file node_modules/@angular/router/config.d.ts (which was pointed in index.d.ts) and indeed - there is no 'name' field in RouterConfig (Route class). 我检查文件node_modules/@angular/router/config.d.ts(在index.d.ts中指出),确实 - 在RouterConfig(Route类)中没有'name'字段。 So how to do named routes in Angular2 ? 那么如何在Angular2中做命名路线?

There is a way to have named routes in new Angular2 router (which don't support it) (the main idea is from checked answer - @Michael Robison) : 有一种方法可以在新的Angular2路由器中使用命名路由(不支持它)(主要思想来自已检查的答案 - @Michael Robison):

in file app.routes.ts i have: 在文件app.routes.ts我有:

...
import { Url } from './common/url';

export const routes: RouterConfig = [
  { path: '',       component:  LoginForm },
  { path: Url.to('login'),  component: LoginForm },
  { path: Url.to('home'), component: Home, canActivate: [AllAuthGuard] },
  { path: Url.to('clients'), component: Cliens, canActivate: [AdminAuthGuard] },
  { path: Url.to('projects'), component: Projects, canActivate: [AdminAuthGuard] },
  ...
  { path: '**',     component: LoginForm },
];

And in /app/common/url.ts I have something similar to (i make below code here by hand without checking it): 在/app/common/url.ts我有类似的东西(我在这里手工编写代码而不检查它):

export class Url {
    map = {
      'login': 'my-super-login',
      'home': 'my-link-home',
      'clients': 'favourite-clients',
      'projects': 'bets-projects',
    }

    public static to(routingName : string) {
        return this.map[routingName];
    }

}

And every where in your project in links you must also use Url.to(...) method (in Controllers make method links(route) which call Url.to, and use it in template...). 在项目中链接的每个位置,您还必须使用Url.to(...)方法(在控制器中创建调用Url.to的方法links(route) ,并在模板中使用它...)。 Above Url static class is theoretical. 以上Url静态类是理论上的。 In practice i user polyglot.js small library to have support to parameters and translation for url - so my Url.to method looks something like that: 在实践中我使用polyglot.js小库来支持参数和url的翻译 - 所以我的Url.to方法看起来像这样:

export class Url {
    public static to(routingName : string, values?:any) {
        return Lang.t('routing.'+routingName, values);
    }
}

Which use class: 哪个使用类:

var Polyglot = require('../../../../node_modules/node-polyglot/build/polyglot.min.js');

import { Auth } from '../';
import { en } from './en';
import { pl } from './pl';

export class Lang {
  private static instance = null;
  public polyglot:any;
  private static emergencyLang = 'en';

  constructor() {
      this.polyglot = new Polyglot();
      this.polyglot.extend({
          en,  
          pl,
      });
      if(Lang.instance) return;
      Lang.instance = this;
  }

  public static t(key:string, values?:any) {
      let self = Lang.getInstance();
      let user = Auth.user();
      let userLang = user ? user.lang : (navigator.language || navigator.userLanguage);
      let langKey = userLang + '.'+key;
      if(self.polyglot.has(langKey)) return self.polyglot.t(langKey, values);

      return self.polyglot.t(Lang.emergencyLang + '.'+key, values);
  }


  private static getInstance() {
      if(Lang.instance == null) Lang.instance = new Lang();
      return Lang.instance;
  }

}

For instance in ./en.ts I have: 例如在./en.ts我有:

export const en = {
    routing : {
        login: 'login',
        clients: 'my-clients',
        projects: 'my-projects',
        "project.pages": 'my-projects/%{project_id}/pages',
        ...
    }

    login : "Login"
    ....
}

And similar for other languages. 和其他语言类似。

=== EDIT: AoT support === ===编辑:AoT支持===

I notice that aboce solution (Url class) not cooperating with AoT. 我注意到aboce解决方案(Url类)没有与AoT合作。 Using command npm run build:aot in angular-starter we will see below error: 使用命令npm run build:aot in angular-starter我们将看到以下错误:

Error: Error encountered resolving symbol values statically. 错误:静态解析符号值时遇到错误。 Calling function 'Url', function calls are not supported. 调用函数'Url',不支持函数调用。 Consider replacing the function or lambda with a reference to an exported function, resolving symbol ROUTES in... 考虑使用对导出函数的引用替换函数或lambda,在...中解析符号ROUTES

Because on AoT compilation app.routes.ts file is compiled using metadata js subset . 因为在AoT编译app.routes.ts文件是使用元数据js子集编译的。 So below I give solution for named routes (with parameters) writen using compatibile with AoT js subset: 所以下面我给出了使用与AoT js子集兼容的命名路由(带参数)的解决方案:

export class Url {

    public static to(routingName: string, values?: any) {

        return {
            'clients' : 'favourite-clients/' + values['client_id'],
            'projects' : 'projects/' + values['project_id'] + '/best',
            ...
        }[routingName];
    }

}

May be using some trick in app.routes.ts and above Url.to method it will be also posible to incorporate multilang compatibile with AoT. 可能在app.routes.ts和Url.to方法中使用了一些技巧,它也可以将multilang compatiblebile与AoT结合使用。

RC.3 is most recent Angular2 version and the new router V3-alpha7 doesn't support names. RC.3是最新的Angular2版本,新的路由器V3-alpha7不支持名称。 Name was removed because it didn't work out with lazy loading of routes. 名称已删除,因为它没有延迟加载路由。

我只想使用ng2-translate并为JSON文件中的每种语言创建链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM