用这个代码
ngOnInit() {
this.router.events.subscribe((val) => {
if (this.router.url.indexOf('page') > -1) {
let id = this.activedRoute.snapshot.params['Id']
this.busy = this.httpCall.get('/pub/page/GetPageById/' + id)
.subscribe(data => {
this.pages = <Page[]>data
})
console.log(id)
}
})
}当我导航到domain.com/#/en/page/13时,它会按预期记录13。
但是,当我导航到id为27的页面时,它会记录:13 13 27。
当我导航回13日志时,拥有:27 27 13。
为什么会这样呢?
发布于 2017-05-29 13:41:02
从日志中可以看到,在每次更改路由时,您的订阅都会被调用三次。因此,这意味着可以观察到的事件会发出许多信号,但你只对其中一个感兴趣。
ngOnInit() {
this.getData();
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => this.getData());
}
getData(){
if (this.router.url.indexOf('page') > -1) {
let Id = this.activedRoute.snapshot.params['Id'];
this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
.subscribe(
data => {
this.pages = <Page[]>data;
});
console.log(Id);
}
}发布于 2017-05-29 13:30:02
当您破坏组件时,您必须取消订阅。
首先你必须
import { OnDestroy } from '@angular/core;'那你就得
export class myClass implements OnInit, OnDestroy {
myObserver = null;
// Rest of your code
}在你的ngOnInit里,你必须
ngOnInit() {
this.myObserver = this.router.events.subscribe(...);
}然后,创建一个函数
ngOnDestroy() {
this.myObserver.unsubscribe();
}发布于 2020-02-18 15:47:01
当您在ngOnInit或Constructor上编写“ngOnInit”时会发生这种情况,为了解决这个问题,您应该将它写在其他函数上,比如:
onRouteChange () {
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
if (this.router.url.indexOf('page') > -1) {
let Id = this.activedRoute.snapshot.params['Id'];
this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
.subscribe(
data => {
this.pages = <Page[]>data;
});
console.log(Id);
}
}
})
}但是,在使用"this.router.events.subscribe“时,还需要考虑另一个问题,在此函数中写入的所有内容都是在页面中导航时发生的,因此最好使用这一行来防止在每次路径更改时运行它:
import {Router, NavigationStart} from '@angular/router';
onRouteChange () {
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
// this line
if(event.url == 'your_page_path')
if (this.router.url.indexOf('page') > -1) {
let Id = this.activedRoute.snapshot.params['Id'];
this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
.subscribe(
data => {
this.pages = <Page[]>data;
});
console.log(Id);
}
}
})
}https://stackoverflow.com/questions/44243653
复制相似问题