Angular 2路由器(ES5)在页面重新加载时不起作用

时间:2016-02-01 18:20:07

标签: angular

我写了一个简单的Angular 2应用程序。除了一件事,一切都很好。当我点击路由器链接时,更改了Url并加载了组件,然后当我重新加载页面时,我找不到 404 。无法理解为什么?

这是我的代码:

(function(app) {


  app.AppComponent =
    ng.core.Component({
      selector: 'my-app',
      template: '<a [routerLink]="[\'Component1\']">Component1</a>' + 
                '<a [routerLink]="[\'Component2\']">Component2</a>' + 
                '<router-outlet></router-outlet>',
      directives: [
            ng.router.ROUTER_DIRECTIVES
      ]
    })
    .Class({
      constructor: function() {}
    });


    app.AppComponent = ng.router.RouteConfig([

    {
        path: '/component1', component: app.Component1, name: 'Component1' 
    },
    {
        path: '/component2', component: app.Component2, name: 'Component2' 
    }
    ]) ( app.AppComponent );


})(window.app || (window.app = {}));

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:5)

这是一个浏览器功能 默认情况下,Angular使用HTML5 pushstate(Angular slang中的PathLocationStrategy) 您需要一台服务器来处理请求index.html之类的所有请求,或者切换到HashLocationStrategy(在路由的URL中使用#)https://angular.io/docs/js/latest/api/router/HashLocationStrategy-class.html

另见https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/

切换到HashLocationStrategy使用

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

确保您拥有所有必需的导入

import {provide} from 'angular2/angular2';
import {
  HashLocationStrategy
  LocationStrategy,
  ROUTER_PROVIDERS,
} from 'angular2/router';
相关问题