我正在使用Angualr2 Beta开发产品。
我希望改变位置政策。
我希望网址像
localhost / app.html#location1
(我认为alpha版本与上面类似)
不是
localhost / app.html /#/ location1
按provide(LocationStrategy, {useClass: HashLocationStrategy})
不是
本地主机/的 app.html / LOCATION1
按provide(LocationStrategy, {useClass: PathLocationStrategy})
因为不适合我的情况需要网络服务器设置。但我不想付出额外的工作。而且我足以让我能够为哈希样式路由添加书签。
如果您对此有所了解。请告诉我。
谢谢。
答案 0 :(得分:0)
您需要自定义LocationStrategy
。以下是HashLocationStrategy
的改编版本,以满足您的需求。
prepareExternalUrl()
方法是我进行更改的地方。我确定有一种方法可以阻止Angular 2从URL中删除html文件名,但作为一种快速解决方法,我已将其添加回使用prepareExternalUrl()
方法。
值得注意的是,以这种方式配置URL会阻止深层链接处理初始页面加载。后续导航按预期工作。
import { Injectable, Inject, Optional, platform } from 'angular2/core';
import { LocationStrategy, PlatformLocation, APP_BASE_HREF } from 'angular2/router';
import { joinWithSlash, normalizeQueryParams } from 'angular2/src/router/location_strategy';
import { UrlChangeListener } from 'angular2/src/router/platform_location';
import { isPresent } from 'angular2/src/facade/lang';
@Injectable()
export class CustomHashLocationStrategy extends LocationStrategy {
private _baseHref: string = '';
constructor(private _platformLocation: PlatformLocation,
@Optional() @Inject(APP_BASE_HREF) _baseHref?: string) {
super();
if (isPresent(_baseHref)) {
this._baseHref = _baseHref;
}
}
onPopState(fn: UrlChangeListener): void {
this._platformLocation.onPopState(fn);
this._platformLocation.onHashChange(fn);
}
getBaseHref(): string { return this._baseHref; }
path(): string {
// the hash value is always prefixed with a `#`
// and if it is empty then it will stay empty
var path = this._platformLocation.hash;
// Dart will complain if a call to substring is
// executed with a position value that extends the
// length of string.
return (path.length > 0 ? path.substring(1) : path) +
normalizeQueryParams(this._platformLocation.search);
}
prepareExternalUrl(internal: string): string {
var url = joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('app.html#' + url.substring(1)) : url;
}
pushState(state: any, title: string, path: string, queryParams: string) {
var url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.pushState(state, title, url);
}
replaceState(state: any, title: string, path: string, queryParams: string) {
var url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.replaceState(state, title, url);
}
forward(): void { this._platformLocation.forward(); }
back(): void { this._platformLocation.back(); }
}