キャメルケースを使用できます。回答の最後に使用されていますか?
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
を使用するか、数式/パターンを使用する必要があります
あなたの現在のURLは http://stackoverflow.com/questions/38613960/angular2-using-router-subscribe-to-watch-url-change
と言っています。
私はAの後、最も深い可能なタイトルをつかむために、再帰的ヘルパーメソッドを使用します。あなたは
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のようなものになります。部分文字列または正規表現は、URLの文字カウントが異なるため、苦痛になります。 「タイトル1」を最終結果として期待していたので、if文をやったのです。 – nCore
申し訳ありませんがあなたを明確に得ることができません。あなたに 'title-1'を渡すことはありませんが、' Title 1'を与えています。 watch-subscribe-to-url-change。お返事の終わりに私の編集を参照してください – Sami
ありがとう、いいえ、それはタイトル1を与えませんが、今それは私にタイトル1を与えます。(ダッシュボードプレビューテスト)ダッシュボードプレビューテストよりも好きな方法はありません。私のルートに「Dashboard-Preview-Test」というパスを作っていない限り、それはURLにwww.mysite.com/Dashboard-Preview-Testを与えます。 – nCore