编辑您可以使用骆驼案件。看到它用在答案的末尾部分
this.title = camelize(lastPartOfUrl.replace(/-/g,' '));
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
答案是使用一些逻辑/技巧。
证明用简单的JavaScript(必须的工作液)
this._router.events.subscribe((event) => {
console.log('route changed');
var url = window.location.toString();
var ar = url.split('/');
var lastPartOfUrl = ar[ar.length-1];
this.title = "Title "+lastPartOfUrl ;
});
随着角路径(前提是你不喜欢上面的简单的方法)。现在同样的逻辑,但只有当.path()
工作正常进行你
this._router.events.subscribe((event) => {
console.log('route changed');
var lastPartOfUrl = this.location.path();
this.title = "Title "+lastPartOfUrl ;
});
编辑
上面会给你Title 1
。如果你真的想要动态标题,那么你必须遵循某种模式。要么你必须使用if
或者你必须使用一些公式/模式
说你当前的网址是 http://stackoverflow.com/questions/38613960/angular2-using-router-subscribe-to-watch-url-change
。你可以得到最好的来自该网址的标题也能像
this._router.events.subscribe((event) => {
console.log('route changed');
var lastPartOfUrl = this.location.path();
//this.title = lastPartOfUrl.replace(/-/g,' '); //following will be the result
//angular2 using router subscribe to watch url change
this.title = camelize(lastPartOfUrl.replace(/-/g,' '));
//Angular2 Using Router Subscribe To Watch Url Change
});
我的头脑中也有这种方法,但通过这样做,我会拥有像title-1或dashboard-3之类的东西。子字符串或正则表达式这将是一个痛苦,因为网址有不同的字符数。希望将“Title 1”作为最终结果,我想这就是为什么我做了if语句。 – nCore
抱歉,无法让你清楚。它不会给你'标题1',但它给'标题1'。订阅到手表的URL变化。请参阅我的编辑结尾处的答案 – Sami
谢谢,不,它不会给第1标题,但现在它会给我标题1.没有像(仪表板预览测试)那样的方式(仪表板预览测试)。那么除非我在route.ts中创建路径:'Dashboard-Preview-Test',但是这会给我www.mysite.com/Dashboard-Preview-Test在url中。 – nCore