本文介绍了Angular2 Observable BehaviorSubject 服务不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自己的可观察服务,但是在我从服务中获取初始数据后,对服务的任何更新都不会传播给任何订阅者.服务看起来像这样:

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)
    });
};

在控制台日志中给出了一个陷阱.但是在其他地方用 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ünter Zöchbauer 所说的内容.您是否以单身人士的身份提供服务?

Also check for what Günter Zöchbauer said. Are you providing the service as a singleton?

这篇关于Angular2 Observable BehaviorSubject 服务不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:59