Angular2 наблюдать за изменением маршрута
@RouteConfig([
{path: '/about', name: 'About', component: About, useAsDefault: true},
{path: '/test', name: 'Test', component: Test}
])
export class MyApp {
router: Router;
location: Location;
isCollapsed: boolean = true;
// ON ROUTE CHANGE {
this.isCollapsed = true;
// }
constructor(router: Router, location: Location) {
this.router = router;
this.location = location;
}
}
Мне нужно изменить значение переменной при каждом изменении маршрута, как наблюдать за этим событием в Angular 2.x?
Ответы
Ответ 1
В окончательной версии Angular (например, Angular 2/4) вы можете сделать это
this.router.events.subscribe((event) => {
console.log(event);
if(event.url) {
console.log(event.url);
}
});
Каждый раз, когда маршрут изменяется, events
Observable имеет информацию.
Нажмите здесь для docs.
Ответ 2
Если вы используете
"@angular/router": "3.0.0-alpha.7",
"@angular/router-deprecated": "2.0.0-rc.2",
затем
this.router.events.subscribe((event) => {
console.log('route changed');
});
Ответ 3
Вот что я использую в своем приложении. Вы можете подписаться на экземпляр Route для отслеживания изменений.
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*detect changes*/)
}
}
Ответ 4
Если вы хотите поймать событие при изменении маршрута и инициализировать некоторый код, например jQuery, используйте OnActive
hook.
Например:
import {Component} from 'angular2/core';
import {OnActivate,ComponentInstruction} from "angular2/router";
declare var $:any;
declare var Foundation:any;
@Component({
templateUrl :'/app/templates/home.html'
})
export class HomeComponent implements OnActivate{
routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction)
{
new Foundation.Orbit($("#es-slide-show"), {});
return true;
}
}