Plunkr:https://plnkr.co/edit/arROwxsFYraSBeAZCIYF?p=preview
我正在尝试订阅观察者,但我无法让它发挥作用。由于某种原因,从不激活subscribe方法,notifyAboutChange
运行并且传递了正确的id但是在调用next
之后,subscribe方法似乎没有接受它被调用。
包含观察者的服务:
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 ....
}
答案 0 :(得分:2)
我认为可能是因为您没有共享相同的服务实例。您可以在引导应用程序时定义相应的提供程序:
bootstrap(AppComponent, [ ApiService ]);
不要忘记从components /指令的providers
属性中删除服务。
请注意,如有必要,您可以限制服务范围。例如,通过在包含/使用组件和指令的组件中定义它。
请参阅此plunkr:https://plnkr.co/edit/lGgNq5HpqFZCQfGl0Tpw?p=preview。