私はホームページにいるかどうかをチェックして何かを行い、他のページでそれをしないでください。また、そのコンポーネントはすべてのページにインポートされました。角2現在のルートを取得
私がホームページにいる場合、そのコンポーネントでどのように検出できますか?
おかげ
私はホームページにいるかどうかをチェックして何かを行い、他のページでそれをしないでください。また、そのコンポーネントはすべてのページにインポートされました。角2現在のルートを取得
私がホームページにいる場合、そのコンポーネントでどのように検出できますか?
おかげ
は、ネイティブウィンドウオブジェクトからこれらのいずれかを試してみてください
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({...})
export class MyComponent {
constructor(private router:Router) {
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
console.log("current url",event.url); // event.url has current url
// your code will goes here
}
});
}
}
おかげで、私はそれを行う:D –
このことを除いて'/'はURLとして常に表示されます。つまり、現在のページは表示されません。サイトのルートのみが表示されます –
正しく動作します。私はHomeComponentにいるときに/ homeを表示しています。 – anonym
import { RouterStateSnapshot } from '@angular/router';
constructor(private state: RouterStateSnapshot) {
console.log("Current Url Path", state);
}
このスニペットは質問に答えるかもしれませんが、いくつかの説明が確かにそれを改善するでしょう。 –
4.4.4では、[RouterStateSnapshot](https://github.com/angular/angular/blob/4.4.4/packages/router/src/router_state.ts#L314-L350)は注射可能なサービスではありません。 –
、これを試してみてください。
console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);
の
//ここにコードがあります if(event.url === '/'){ this.showComponent = false; } else { this.showComponent = true; } –
それを試してみてください
import { Router } from '@angular/router';
export class MyComponent implements OnInit {
constructor(private router:Router) { ... }
ngOnInit() {
let currentUrl = this.router.url; /// this will give you current url
// your logic to know if its my home page.
}
}
可能な複製[現在のルートを取得する方法](http://stackoverflow.com/questions/34597835/how-to-get-current-route) – Adam