我在不同组件中使用路由器更改观察器。我想让它可重用,所以我不需要将此代码包含在每个需要它的组件中。我怎么能做到这一点?
changeObserver = null;
constructor(private router: Router) {
this.changeObserver = router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
if(event instanceof NavigationEnd)
// change of url
//--
// call some component functions - different for each component
//--
});
}
ngOnDestroy()
{
this.changeObserver.unsubscribe();
}
答案 0 :(得分:1)
您可以创建一个抽象类,该类实现您想要的内容,并扩展您希望具有该路由实现的类。
abstract class BaseComponent {
observer;
constructor() {
this.observer = [1, 2, 3].forEach(number => {
this.do(number);
});
}
onDestroy() {
// this.observer.unsubscribe();
}
abstract do(number);
}
并实现:
class Component extends BaseComponent {
do(number) {
console.log(number);
}
}
答案 1 :(得分:1)
您可以创建一个单独的Service类来处理这一小段代码,并为您提供处理异步操作的回调选项。
@Injectable()
export class NavigationService {
private changeObserver;
constructor(private router: Router) {
}
execute(callback) {
this.changeObserver = router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
if (event instanceof NavigationEnd)
callback();
});
}
}
constructor(private NavigationService: navigationService) {
this.navigationService.execute(()=>{
//your code goes here.
});
}
注意:由于代码是直接在stackoverflow编辑器中编写的,因此可能会出现一些拼写错误和语法错误。请纠正自己。