Angular2 Observable BehaviorSubject服务无法正常工作 [英] Angular2 Observable BehaviorSubject service not working
问题描述
我正在尝试创建自己的可观察服务,但是从该服务获取初始数据后,该服务的任何更新都不会传播到任何订户.服务看起来像这样:
I'm trying to create my own observable service but after i get the initial data from the service, any updates to the service aren't propagated to any subscribers. Service looks like this:
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs/Rx';
@Injectable()
export class DataService {
keys : number[] = [4,5,1,3,2];
private data :BehaviorSubject<number[]> = new BehaviorSubject(this.keys);
constructor() {};
public setKey(i:number, val:number) :void {
this.keys[i]=val;
this.data.next(this.keys);
}
public getData() :Observable<number[]> {
return new Observable(fn => this.data.subscribe(fn));
}
public getKeys() :number[] {
return this.keys;
}
}
使用该服务的组件可以很好地获取初始数据.该组件在构造函数中获取其数据:
the component using the service gets the initial data just fine. that component gets its data in the constructor:
constructor(public dataService: DataService) {
dataService.getData().subscribe(data => {
console.log("Gotcha!");
this.data.datasets[0].data = data)
});
};
会在控制台日志中显示一个Gotcha.但是在其他地方使用setKey(2,3)更新数据后,我期望 this.data.next(this.keys); 发送数据给所有用户,数据将在该组件内部进行相应更新.但是没有数据发送给订户.
which gives one Gotcha in the console log. But after updating the data with setKey(2,3) somewhere else, i was expecting the this.data.next(this.keys); to send data to all subscribers and data would be updated inside that component accordingly. but no data is sent to the subscribers..
我认为我想出了Observables,但是如果我在这里错过了重点,请不要友善;)任何朝着正确方向的指针将不胜感激!
i thought i figured the Observables out but please dont be friendly if i'm missing the point here ;) any pointers in the right direction will be greatly appreciated!
推荐答案
每次发出一个值时,都应该创建一个新对象,而不是发出相同的变异对象.这样可以保护您免受更改检测问题的影响.最好在更改时始终为this.keys
分配一个新对象.
Every time you emit a value, you should create a new object instead of emitting the same mutated object. That will protect you from change detection issues. It'd be better to always assign a new Object to this.keys
when you change it though.
this.data.next([...this.keys]);
您可以在此处使用asObservable()
public getData(): Observable<number[]> {
return this.data.asObservable();
}
还要检查GünterZöchbauer怎么说.您是否以单身人士的身份提供服务?
Also check for what Günter Zöchbauer said. Are you providing the service as a singleton?
这篇关于Angular2 Observable BehaviorSubject服务无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!