Yanıtlar:
Açısal 2'de subscribebir Yönlendirici örneğine (Rx olayı) yapabilirsiniz . Yani böyle şeyler yapabilirsiniz
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*whatever*/)
}
}
Düzenle (rc.1'den beri)
class MyClass {
constructor(private router: Router) {
router.changes.subscribe((val) => /*whatever*/)
}
}
Düzenleme 2 (2.0.0'dan beri)
ayrıca bakınız: Router.events doc
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
filteroperatörü ile olayları kolayca filtreleyebilirsiniz . router.events.pipe(filter(e => e instanceof NavigationEnd).subscribe((e) => { ... }
RxJS 6
router.events.pipe(filter(event => event instanceof NavigationStart))
Peilonrayz sayesinde (aşağıdaki yorumlara bakınız)
yeni yönlendirici> = RC.3
import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router';
constructor(router:Router) {
router.events.forEach((event) => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
});
}
Ayrıca verilen etkinliğe göre de filtreleyebilirsiniz:
import 'rxjs/add/operator/filter';
constructor(router:Router) {
router.events
.filter(event => event instanceof NavigationStart)
.subscribe((event:NavigationStart) => {
// You only receive NavigationStart events
});
}
Önceki ve güncel olayı almak için pairwiseoperatörü kullanmak da iyi bir fikirdir. https://github.com/angular/angular/issues/11268#issuecomment-244601977
import 'rxjs/add/operator/pairwise'; import { Router } from '@angular/router; export class AppComponent { constructor(private router: Router) { this.router.events.pairwise().subscribe((event) => { console.log(event); }); }; }
Argument of type '(event: Event) => void' is not assignable to parameter of type
Argument of type '(event: Event) => void' is not assignable to parameter of typehata, filtre snippet'inizde NavigationEvent yerine Event türündeki bir nesneye abone olmanızdır.
İçin açısal 7 birisi gibi yazmalıdır:
this.router.events.subscribe((event: Event) => {})
Ayrıntılı bir örnek aşağıdaki gibi olabilir:
import { Component } from '@angular/core';
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
// Show loading indicator
}
if (event instanceof NavigationEnd) {
// Hide loading indicator
}
if (event instanceof NavigationError) {
// Hide loading indicator
// Present error to user
console.log(event.error);
}
});
}
}
7 Eğik , eğer istersen subscribeetmekrouter
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
constructor(
private router: Router
) {
router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
console.log(event.url);
});
}
Açısal 4.x ve üstü:
Bu, ActivatedRoute sınıfının url özelliği kullanılarak aşağıdaki gibi elde edilebilir ,
this.activatedRoute.url.subscribe(url =>{
console.log(url);
});
Not:
Sağlayıcıyı angular/routerpaketten içe aktarmanız ve enjekte etmeniz gerekir
import { ActivatedRoute } from '@angular/router`
ve
constructor(private activatedRoute : ActivatedRoute){ }
Yönlendirici 3.0.0-beta.2 olmalıdır
this.router.events.subscribe(path => {
console.log('path = ', path);
});
Açısal 6 ve RxJS6'da:
import { filter, debounceTime } from 'rxjs/operators';
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
debounceTime(40000)
).subscribe(
x => {
console.log('val',x);
this.router.navigate(['/']); /*Redirect to Home*/
}
)
import {Router, NavigationEnd} from "@angular/router"
Buradaki cevaplar doğru router-deprecated. Şunun en son sürümü için router:
this.router.changes.forEach(() => {
// Do whatever in here
});
veya
this.router.changes.subscribe(() => {
// Do whatever in here
});
İkisi arasındaki farkı görmek için lütfen bu SO sorusuna göz atın .
Düzenle
En son için yapmanız gerekenler:
this.router.events.subscribe(event: Event => {
// Handle route change
});
routergüncellendi (Cevabımı henüz güncellemedim), bu yüzden en son nasıl olduğundan emin değilim. Çünkü routeryazdım, yapamazsın. @akn
Açısal 8'de şunları yapmalısınız: this.router.events.subscribe((event: Event) => {})
Misal:
import { Component } from '@angular/core';
import { Router, Event } from '@angular/router';
import { NavigationStart, NavigationError, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
//Router subscriber
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
//do something on start activity
}
if (event instanceof NavigationError) {
// Handle error
console.error(event.error);
}
if (event instanceof NavigationEnd) {
//do something on end activity
}
});
}
}
Bileşende, şunu denemek isteyebilirsiniz:
import {NavigationEnd, NavigationStart, Router} from '@angular/router';
constructor(private router: Router) {
router.events.subscribe(
(event) => {
if (event instanceof NavigationStart)
// start loading pages
if (event instanceof NavigationEnd) {
// end of loading paegs
}
});
}
Güzergah değişikliği olaylarını aşağıdaki şekilde yakalayın ...
import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';
@Component({
selector: "my-app",
templateUrl: "app/app.component.html",
styleUrls: ["app/app.component.css"]
})
export class AppComponent {
constructor(private cacheComponentObj: CacheComponent,
private router: Router) {
/* Route event types
NavigationEnd
NavigationCancel
NavigationError
RoutesRecognized
*/
router.events.forEach((event: NavigationEvent) => {
//Before Navigation
if (event instanceof NavigationStart) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
//After Navigation
if (event instanceof NavigationEnd) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
});
}
}
Konum çalışmaları ...
import {Component, OnInit} from '@angular/core';
import {Location} from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private location: Location) {
this.location.onUrlChange(x => this.urlChange(x));
}
ngOnInit(): void {}
urlChange(x) {
console.log(x);
}
}
çoğu çözüm doğru yukarıda, ancak bu sorun karşılaştığım bu birden fazla kez 'Gezinme yayar' olayı. herhangi bir rota değiştirmek oldu zaman bu olay tetiklenir. Yani duymak Açısal 6 için komple bir çözümdür.
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
export class FooComponent implements OnInit, OnDestroy {
private _routerSub = Subscription.EMPTY;
constructor(private router: Router){}
ngOnInit(){
this._routerSub = this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe((value) => {
//do something with the value
});
}
ngOnDestroy(){
this._routerSub.unsubscribe();
}
}
@Ludohen cevap harika, ancak kullanmak istemiyorsanız instanceofaşağıdakileri kullanın
this.router.events.subscribe(event => {
if(event.constructor.name === "NavigationStart") {
// do something...
}
});
bu şekilde geçerli olay adını dize olarak kontrol edebilirsiniz ve olay meydana geldiğinde işlevinizi yapmayı planladığınız şeyi yapabilirsiniz.
Eventtür Atom'da hataya neden oluyor, bu yüzden onu kullanmadım
instanceOf, örneğin üretim kodunda da çalışmasını tercih etmelisiniz . if(event instanceOf NavigationStart) {
if(event instanceof NavigationStart)
Angular5 uygulaması ile çalışıyorum ve aynı sorunla karşı karşıyayım. Açısal Belgelerden geçerken yönlendirici olaylarını işlemek için en iyi çözümü sağlarlar. aşağıdaki belgeleri kontrol edin.
Açısaldaki Yönlendirici Olayları Açısaldaki Güzergah olayları5
Ancak özellikle söz konusu olay için NavigationEnd Etkinliğine ihtiyacımız var
Gezinme başarıyla sona erdiğinde tetiklenen bir etkinliği temsil eder
Bu nasıl kullanılır?
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRouteSnapshot, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit(): void {
//calls this method when navigation ends
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
//calls this stuff when navigation ends
console.log("Event generated");
}
});
}
}
Ne zaman kullanılır?
Benim durumumda, uygulama, kullanıcılar, Yöneticiler gibi tüm kullanıcılar için ortak kontrol panelini paylaşıyorum, ancak kullanıcı türlerine göre bazı navbar seçeneklerini göstermem ve gizlemem gerekiyor.
Bu nedenle url değiştiğinde, yanıt olarak oturum açmış kullanıcı bilgilerini döndüren hizmet yöntemini çağırmam gerekiyor, çünkü daha sonraki işlemler için gideceğim.
Aşağıdaki KIND çalışır ve sizin için zor olabilir.
// in constructor of your app.ts with router and auth services injected
router.subscribe(path => {
if (!authService.isAuthorised(path)) //whatever your auth service needs
router.navigate(['/Login']);
});
Ne yazık ki bu, yönlendirme sürecinde istediğimden daha sonra yönlendiriyor. onActivate()Orijinal hedef bileşeninin yönlendirme öncesinde denir.
@CanActivateHedef bileşen üzerinde kullanabileceğiniz bir dekoratör var ama bu a) merkezi değil ve b) enjekte edilen hizmetlerden faydalanmıyor.
Herhangi bir işin yapılmadan önce merkezi olarak yetkilendirmenin daha iyi bir yolunu önermek harika olurdu. Eminim daha iyi bir yol olmalı.
Bu geçerli kodum (Güzergah değişikliğini dinlemek için nasıl değiştirebilirim?):
import {Component, View, bootstrap, bind, provide} from 'angular2/angular2';
import {ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
import {Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import { Todo } from './components/todo/todo';
import { About } from './components/about/about';
@Component({
selector: 'app'
})
@View({
template: `
<div class="container">
<nav>
<ul>
<li><a [router-link]="['/Home']">Todo</a></li>
<li><a [router-link]="['/About']">About</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
</div>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', redirectTo: '/home' },
{ path: '/home', component: Todo, as: 'Home' },
{ path: '/about', component: About, as: 'About' }
])
class AppComponent {
constructor(location: Location){
location.go('/');
}
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'})]);
RC 5'ten beri böyle yapıyorum
this.router.events
.map( event => event instanceof NavigationStart )
.subscribe( () => {
// TODO
} );
Sadece AppRoutingModule üzerinde değişiklikler yapın
@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
exports: [RouterModule]
})
Ben böyle bir şey yazmak istiyorum:
ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
.subscribe(() => {
} );
}
ngOnDestroy() {
this.routed.unsubscribe();
}
event._root.children[0].value._routeConfig.datadaha iyi bir yol olabilir umarım veri elde edebiliyoruz