Angular 2 Router(ES5)在页面重新加载时不起作用 [英] Angular 2 Router (ES5) doesn't work on page reload
问题描述
我编写了一个简单的Angular 2应用程序.除了一件事,一切都很好.当我单击路由器链接时,URL更改并且组件被加载,然后当我重新加载页面时,我发现未找到 404 .不明白为什么?
I wrote a simple Angular 2 application. Everything works just fine except one thing. When I click on the router link, Url is changed and component is loaded, then when I reload the page I get 404 not found. Can not understand why?
这是我的代码:
(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 = {}));
任何帮助将不胜感激!
推荐答案
这是浏览器功能.
默认情况下,Angular使用HTML5 pushstate(在Angular lang语中为PathLocationStrategy
).
您可能需要一台服务器来处理所有请求,就像正在请求index.html
一样,或者您切换到HashLocationStrategy
(路由的URL中带有#)
That's a browser feature.
Angular by default uses HTML5 pushstate (PathLocationStrategy
in Angular slang).
You either need a server that processes all requests like it were requesting index.html
or you switch to HashLocationStrategy
(with # in the URL for routes) 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})
]);
确保您拥有所有必需的进口商品
ensure you have all required imports
import {provide} from 'angular2/angular2';
import {
HashLocationStrategy
LocationStrategy,
ROUTER_PROVIDERS,
} from 'angular2/router';
这篇关于Angular 2 Router(ES5)在页面重新加载时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!