当我尝试使用 next() 添加变量时,BehaviorSubject 为 next 函数提供错误."我收到错误 this.count.next is not a function" [英] 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"

查看:38
本文介绍了当我尝试使用 next() 添加变量时,BehaviorSubject 为 next 函数提供错误."我收到错误 this.count.next is not a function"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 服务内部,我有一个变量计数,我想在它更新时观察它,我想将该更新的值设置为不同组件中的另一个变量.

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 5.4.3 最新版本!

} rxJs version 5.4.3 latest!

推荐答案

试试这个:

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

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

您遇到的问题是您在函数内的 this 被更改(即指向其他内容)的上下文中使用 addCount.在打字稿中使用基于 lamda 的函数可确保不会发生这种情况.然而,这不是总是使用它们的借口.

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.

我建议您阅读一下 lambda/箭头函数,在 javascript打字稿.

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.

这篇关于当我尝试使用 next() 添加变量时,BehaviorSubject 为 next 函数提供错误."我收到错误 this.count.next is not a function"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆