1
Plunkr:https://plnkr.co/edit/arROwxsFYraSBeAZCIYF?p=preview角2订阅不执行
我想订阅的观察者,但我不能得到它的工作。订阅方法从未被激活,出于某种原因,notifyAboutChange
运行并且传递了正确的标识,但在调用next
之后,订阅方法似乎无法在被调用时启用。
其中包含了观察者的服务:
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class ApiService {
public notifier = new Subject();
public changeOccurrence$ = this.notifier.asObservable();
constructor() {}
notifyAboutChange(id: string) {
this.notifier.next(id);
}
}
指令,它调用notifyAboutChange
方法:
constructor(private _elementRef: ElementRef, private _renderer: Renderer, private _api: ApiService) {
this.eventHandler = _renderer.listen(_elementRef.nativeElement, ('ontouchstart' in window ? 'touchend' : 'click'), (e) => {
this.isAllChecked = !this.isAllChecked;
for (let checkbox of this.checkboxes) {
if (!checkbox.isDisabled) {
checkbox.isChecked = this.isAllChecked;
}
}
_api.notifyAboutChange(this.componentId);
});
}
组件应订阅:
export class FormCheckboxMultipleComponent implements OnInit, DoCheck {
@Input() model: Array<any>;
@Input() checkboxes: Array<any>;
@Output('modelChange') onModelChange: EventEmitter<any> = new EventEmitter();
@Output() callback: EventEmitter<any> = new EventEmitter();
constructor(private _globals: GlobalVariablesService, private _differs: IterableDiffers, private _api: ApiService) {
this.ns = _globals.ns;
this.differ = _differs.find([]).create(null);
_api.changeOccurrence$.subscribe(
componentId => {
console.log(componentId);
if (this.componentId === componentId) {
for (let checkbox of this.checkboxes) {
let existingIndex = this.findIndex(checkbox, this.model);
if (existingIndex === -1) {
this.model.push(checkbox);
}
else {
this.model.splice(existingIndex, 1);
}
}
}
}
)
}
.... excluded parts ....
}
嗯没有这不是它:/ – Chrillewoodz
您还需要从'组件/指令providers'属性删除服务... –
看到这个plunkr:https://plnkr.co/edit/lGgNq5HpqFZCQfGl0Tpw?p=preview –