【问题标题】:How to change router by typescript in angular2?如何通过angular2中的打字稿更改路由器?
【发布时间】:2015-07-23 03:59:56
【问题描述】:

例如,我像这样使用路由器链接:

<li><a [router-link]="['/start']">Start</a></li>

但是如何通过 typescript 将路由器更改为 /start?

【问题讨论】:

标签: angular angular-new-router


【解决方案1】:

与哈希定位策略相关的小更新。

在 angular2 的最新版本中,bind 方法已被弃用,因此您可以使用 provide 方法更改定位策略。

bootstrap(MyApp, [
  ROUTER_PROVIDERS,provide(LocationStrategy, {useClass: HashLocationStrategy})
]);

【讨论】:

    【解决方案2】:

    我相信你问的是如何在 Angular 2 中配置你的路由。

    • 1) 导入并加载您的路由器
    • 2) 使用@RouteConfig 在组件上设置路由

    • 可选:将井号 (#) 添加到您的网址

    这是一个例子:

    import {Component, View, bind, bootstrap} from 'angular2/angular2';
    import {routerInjectables, routerDirectives, Router, RouteConfig} from 'angular2/router';
    import {LocationStrategy, Location, HashLocationStrategy } from 'angular2/router'; // options2: HTML5LocationStategy
    
    // Components
    import {Home} from 'home';
    import {SomewhereElse} from 'somePlace';
    
    @Component({
      selector: 'app-name'
    })
    @View({
      template: '<router-outlet></router-outlet>',
      directives: [routerDirectives]
    })
    @RouteConfig([
      {path: '/start', as:  component: Home},
      {path: '/place/:placeId', component: SomewhereElse}
    ])
    class AppName {}
    
    bootstrap(AppName, [
      routerInjectables,
      bind(LocationStrategy).toClass(HashLocationStrategy) // for hashbang routes (/#/)
      // alternative: use HTML5LocationStrategy
    ]);
    

    【讨论】:

    • 来到这里寻找如何设置 hashbang 路由并找到了这个,即使它不是问题的一部分 - 谢谢 :)
    • 并且根据@shmck 的有用回答here routerInjectables 已更改为ROUTER_PROVIDERS
    • 对于那些刚刚踏上 Angular 2 美妙世界之旅的人:顺序很重要 - ROUTER_PROVIDERS 应该排在 LocationStrategy 之前。否则它不会工作。 (花了一个小时弄清楚)
    猜你喜欢
    • 2016-04-10
    • 1970-01-01
    • 2016-08-08
    • 2017-08-30
    • 2023-04-05
    • 2019-02-18
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多