BehaviorSubject gives error for next function when i try to add the variable using next().“ I get the error this.count.next is not a function”

无人久伴 提交于 2019-12-12 04:47:51

问题


Inside Angular service i have a variable count, which i want to observe whenever it's updated, i want to set that updated value to another variable in a different component.

import {BehaviorSubject} from "rxjs/BehaviorSubject";
import 'rxjs/Rx';

export class DashboardService{
  count = new BehaviorSubject<number>(0);
  count$=this.count.asObservable();

  addCount(data){
    this.count.next(data);
  }
}

I get the error eventhough i have imported all the relevant libraries .Any idea why i'm getting this? can anyone tell me what's happening with the code ?

} rxJs version 5.4.3 latest!


回答1:


Try this:

export class DashboardService {
    count = new BehaviorSubject<number>(0);
    count$ = this.count.asObservable();

    public addCount = (data) => {
      this.count.next(data);
    }
}

The issue you are encountering is that you are using addCount in a context where this inside the function is altered (i.e. pointing to something else). Using lamda based functions in typescript ensures this can not happen. This is not an excuse for always using them however.

I recommend you read up a bit on lambda/arrow functions, it might also be a good idea to look in to how this works in javascript and in typescript.



来源:https://stackoverflow.com/questions/46452347/behaviorsubject-gives-error-for-next-function-when-i-try-to-add-the-variable-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!