在 Angular2+ 中定义自定义可观察量



我有一个简单的 css 动画库,它允许通过调用loadService.animate(boolean);来显示动画,但遗憾的是它不再起作用,因为我在我的服务中错误地使用了这样的EventEmitter

@Injectable()
export class LoadService {
@Output() animating: EventEmitter<any> = new EventEmitter();
constructor() {}
// User calls animate, we emit an event with the new boolean value
public animate(val: boolean) {
this.animating.emit(val);
}
getValue(): any {
return this.animating;
}
}

并在我的组件中订阅它:

// Animation shown when animate == true
animate: boolean;
ngOnInit(): void {
this.loadService.getValue().subscribe((status: boolean) => {
// Events caught, we change the boolean to display the animation
this.animate = status;
});
this.handleShape();
}

但是我的订阅从未捕获任何内容,因此我想创建一个自定义Observable以便简单地捕获用户调用animate,从而更改布尔值的值。

如何在 Angular2+ 中定义自定义可观察量?在这种情况下,我该如何实现它?

LoadService

在我们的服务中,我们创建了一个默认值为falseBehaviorSubject

private _animate = BehaviorSubject(false);
get animate(): Observable<any>{
return this._animate.asObservable();
}

另外,在LoadService中,要更新我们的observable值,请执行以下操作:

toggleAnimation(value: boolean){
oldValue = this._animate.getValue();
this._animate.next(!oldValue);
}

元件

现在在我们的组件中,您可以像这样订阅它:

constructor(private service: LoadService) {
this.service.animate.subscribe(state => {
// do stuff
console.log(state);
})
};

Angular 团队不鼓励在服务中使用事件发射器,因为它被用作围绕 Subject 的抽象。您可以使用新的键和提供发射的逻辑来创建具有自定义逻辑的可观察量,也可以使用 Subject(可观察量和观察者(将其视为观察者模式的最相似实现。

loadServiceSubject : Subject<any> = new Subject();
loadService$ : Observable<any> = loadServiceSubject.asObservable();
// other code

将主体视为事件发射器和侦听器之间的代理,无论何时调用主题上的下一个函数,发出的值都会被推送到可观察量的所有订阅者。

// in client code
// suppose the service is injected in the constructor
this.animationService.loadService$.subscribe( this.doStuffOnNextCallback );

"事件"发射器只需要在主题本身上调用下一个、错误或完成函数。

// producer code, supposing it's also injected
this.animationService.loadServiceSubject.next(true);

最新更新