The distinctUntilChanged() method is not available for BehaviorSubject

Just delving into the world of Rxjs and attempting to grasp the concept of BehaviourSubject. Here is the code snippet I am working with:

export interface State {
    items: Items[]
}

const defaultState = {
    items: []
};

const _store = new BehaviorSubject<State>(defaultState);

@Injectable()
export class Store {
    private _store = _store;
    changes = this._store.distinctUntilChanged()
        .do(() => console.log('changes'));

    setState(state: State) {
        this._store.next(state);
    }

    getState(): State {
        return this._store.value;
    }

    purge() {
        this._store.next(defaultState);
    }
}

Encountering an error in the console when running the project:

platform-browser.umd.js:1900 EXCEPTION: Error: Uncaught (in promise):
EXCEPTION: Error during instantiation of Store! (StoreHelper -> Store).
ORIGINAL EXCEPTION: TypeError: this._store.distinctUntilChanged is not a function

Requesting assistance to resolve this issue. Open to any suggestions for creating a Store for model objects in a simpler manner.

Grateful for any guidance provided.

Answer №1

If you want to use the distinctUntilChanged operator in RxJs, you have two options. You can either import the entire RxJs library or just the specific operator you need.

import 'rxjs/add/operator/distinctUntilChanged';

For those using RxJs version 5.5 and above, it is recommended to switch to Pipeable Operators for better optimization:

import { distinctUntilChanged } from 'rxjs/operators';

Using Pipeable operators not only helps with building a more efficient codebase, but also facilitates tree shaking for better performance.

If you're interested in learning more about the advantages of Pipeable operators, check out this resource.

I hope this information proves useful for you!

Answer №2

Make sure to import all operators, including do, distinctUntilChanged, and the BehaviorSubject.

import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

Check out this Plnkr demo: http://plnkr.co/edit/Wbqv95EiG8BnzC8BpD7E?p=preview

Also, be cautious with code like private _store = _store as it can be confusing to read, despite functioning as intended.

This content was generated using https://www.typescriptlang.org/play/.

define(["require", "exports"], function (require, exports) {
    "use strict";
    var _store = new BehaviorSubject(defaultState);
    var Store = (function () {
        function Store() {
            this._store = _store;
            this.changes = this._store.distinctUntilChanged()
                .do(function () { return console.log('changes'); });
        }
        Store.prototype.setState = function (state) {
            console.log(_store);
            this._store.next(state);
        };
        Store.prototype.getState = function () {
            return this._store.value;
        };
        Store.prototype.purge = function () {
            this._store.next(defaultState);
        };
        return Store;
    }());
    exports.Store = Store;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Angular 4 enum string mapping reversed

Here is an example of a string enum: export enum TokenLength { SIX = '6', EIGHT = '8', } I am trying to retrieve the string value 'SIX' or 'EIGHT' by reverse mapping this enum. I have attempted various methods: ...

How to dynamically load a component within a class-based Vue component

I am facing an issue with loading two components dynamically using an object map. Info (options-based) SearchBar (class-based) While it works for the options-based component, I encounter an error stating _currentTab is undefined when trying to load a si ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

The SPLoaderError has encountered an issue while loading the component: Unable to load the specified component

While developing a SharePoint app in SPFX Framework, I encountered an issue. When compiling it with gulp build, everything works fine. However, when running gulp serve and adding the app to the workbench, the following error is displayed: [SPLoaderError ...

How can I incorporate MS Teams call recording into my web platform?

Currently in the process of developing a web application using Angular. Successfully integrated video call functionality through Azure Communication. Looking to now incorporate MS Teams call recording feature. Seeking assistance with reference links and s ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Different ways to determine if a given string exists within an Object

I have an object called menu which is of the type IMenu. let menu: IMenu[] = [ {restaurant : "KFC", dish:[{name: "burger", price: "1$"}, {name: "french fries", price: "2$"}, {name: "hot dog", d ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Learn how to retrieve data outside of the .subscribe function in an Angular 2 polling service

// I'm facing an issue where I am unable to assign values from outside the subscribe function to any variable. In my current project, I am fetching JSON content using the http.post() method and storing it in a variable. However, I need to access this ...

Exploring Ionic 2: Utilizing Service and modalCtrl for enhanced functionality

I am relatively new to using Ionic 2. Recently, I created a service that contains all my filters (ModalCtrl) with custom search input and checkboxes. I am passing parameters between them but I am unsure of how to keep the service active and waiting for the ...

Facing issues with building Angular 7 and Ionic 4 - getting error message "TypeError: Cannot read properties of undefined (reading 'kind')"

I need assistance with a problem I am encountering while building my Angular 7 & Ionic 4 application... When I run the ng build --prod command, I encounter the following error: ERROR in ./node_modules/ionic4-auto-complete/fesm5/ionic4-auto-complete.js ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...

Leverage RxJs Pipe for transforming Observables into various data types

Currently, I am dealing with an Observable<Recipe[]> that I need to transform into an array of a different class called ChartData[]. This transformed array will be used as a data source for creating highcharts graphs, such as column charts and pie ch ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

When the state is updated, the Observable fails to retrieve the value from the store

My goal is to update the Observable by connecting it to the store, but I encountered an issue where it didn't get updated when the store received a new value: Within my component, I have declared 'tasks' as an Observable: tasks$: Observable ...

Discrepancy detected in AGM Map printout

When attempting to print my Angular AGM Map from Chrome, I noticed a large grey gap in the map. This gap is visible even when "background graphics" are turned off and it causes the map image below it to shift downwards. If you want to reproduce this issue ...

The Angular 2 http request seems to be failing to reach the web api's get method when using a string parameter overload

Issue at hand is that the initial Get method gets triggered by this particular HTTP request: http://localhost:56690/api/testelements/?name=aeg One would anticipate the second (string overload) method to be invoked due to the presence of a string parameter ...

Establishing a default value as undefined for a numeric data type in Typescript

I have a question regarding setting initial values and resetting number types in TypeScript. Initially, I had the following code snippet: interface FormPattern { id: string; name: string; email: string; age: number; } const AddUser = () => { ...

Utilizing the panelChange event in Angular 2 with NgbAccordion through programmatic invocation

I have a ngbAccordion with a panelChange event that is functioning well. I am curious if there is a way to programmatically call that method in the ngOnInit lifecycle hook? <ngb-accordion #regularAccordion="ngbAccordion" *ngFor="let item of cartItems; ...