我有一个像这样的基本组件:
@Component({})
export class PageComponent implements OnInit, OnDestroy {
title: string;
constructor(
/* other stuff */
protected uiService: UIService) { }
ngOnInit() {
this.uiService.set('title', this.title);
this.uiService.set('something', false);
}
ngOnDestroy() {
/* cleanup */
}
}
和几个扩展它的路由组件,例如:
@ExtendedComponent({ templateUrl: './page-one.component.html' })
export class PageOneComponent extends PageComponent {
title: string = 'Page One Title';
}
@ExtendedComponent({ templateUrl: './page-two.component.html' })
export class PageTwoComponent extends PageComponent {
title: string = 'Page Two Title';
ngOnInit() {
super.ngOnInit();
/* do stuff specific to PageTwoComponent */
this.uiService.set('something', true);
}
}
@ExtendedComponent
装饰者是这样的:
export function ExtendedComponent(annotation: any) {
return (target: Function) => {
const parentTarget = Object.getPrototypeOf(target.prototype).constructor;
const parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
const metadata = new Component({ ...parentAnnotations[0], ...annotation});
Reflect.defineMetadata('annotations', [metadata], target);
const parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget);
const parentParameters = Reflect.getMetadata('parameters', parentTarget);
Reflect.defineMetadata('design:paramtypes', parentParamTypes, target);
Reflect.defineMetadata('parentParameters', parentParameters, target);
};
}
我遇到的问题是UIService
:
@Injectable()
export class UIService {
private buffer: any = {};
private dispatcher: Subject<any> = new Subject();
constructor() {
this.dispatcher
.map(state => this.buffer = { ...this.buffer, ...state })
.debounceTime(50)
.do(() => { /* does something */})
.subscribe();
}
set(key: string, value: any) {
console.log(this.dispatcher.observers); // <-- [MapSubscriber] when working
// <-- [] when not working
this.dispatcher.next({ [key]: value });
}
}
当我在带有其他组件的页面之间导航(此处未显示)时,一切正常。但是,当我从PageOneComponent
导航到PageTwoComponent
(都延伸PageComponent
)时,UIService中的调度程序主题停止工作(console.log
在set方法中显示几次调用后的空数组)。
我不知道为什么会发生这种情况或者可能导致这种情况发生的原因。有什么想法吗?
答案 0 :(得分:1)
您没有将任何函数传递给subscribe()方法。所以订阅被垃圾收集器删除