Subscribing to an array of lists with RxJS Subjects and Observables

I have a quick and simple question. I am using a service called DataStorageServiceService where I have initialized

shopCartProduct = new Subject<ProductModel[]>();
. Now, I have a component named SingleProductComponent and I want to send data into the shopCartProduct as an array. Is it possible for me to interact with the shopCartProduct like a basic array? In other words, can I store and delete data from it in a typical array-like manner?

Answer №1

If you're in search of a Service implementation that resembles the following, then you're on the right track: Please note: The code provided below is untested and should be treated as pseudo code.

export class DataStorageService {

    //A subject available for subscription
    shopCardProduct = new Subject<ProductModel[]>();

    //array storing the products in the shopping cart
    products : ProductModel[] = new Array<ProductModel>() ;

    constructor(){
        this.shopCardProduct = new BehaviorSubject<ProductModel>(new Array<ProductModel>())
    }

    shop(product: ProductModel){
        this.products.push(product);
        this.shopCardProduct.next(this.products);
    }

    getCart(): Subject<ProductModel[]> {
        return this.shopCardProduct;
    }

}

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

Storing data received from httpClient.get and utilizing it in the future after reading

Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends. import ...

Leveraging import and export functionality in TypeScript while utilizing RequireJS as a dependency

I am in the process of transitioning a complex JavaScript application from Backbone/Marionette to TypeScript. While making this shift, I want to explore the benefits of exporting and importing classes using files as modules. Is it necessary to incorporat ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

An issue arose when attempting to compare '[object Object]'. Please note that only arrays and iterables are permitted (Angular 5)

I am facing an issue while attempting to display array data in a standard HTML table. There is a method called soa.service that retrieves data in an array format. service. get(Type: number, Code: string): Observable<Items[]> { var requestOptio ...

Implementing a feature in Angular 7 to retrieve data from local storage and set it as the default redirect route

import { NgModule, OnInit } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuardService } from './../providers'; import { AdminComponent } from './../admin/admin.com ...

Is it possible for a TypeScript function to be used as a React prop even if it conflicts with the function signature's in

Why does the TypeScript type checker allow a prop with a function parameter that does not strictly match the definition? For example, I have a function called callbackImpl = (str: string): number, which is passed as a React prop parameter defined as callb ...

I prefer to conceal the permission-wrapper component tag in the DOM when using Angular

Looking to hide the permission-wrapper component tag from appearing in the DOM. CRUCIAL: The component itself should conceal the component's tag (such as ), and instead display the template's content when necessary. For example, let's crea ...

Arranging React Grid Items with Stylish Overlapping Layout

Is there a way to create a react-grid-layout with 100 grid points width, while ensuring that the grid items do not overlap? https://i.sstatic.net/CQiVh.png (Reducing the number of columns can prevent overlap, but sacrifices the 100-point width resolution ...

Triggering Backbutton actions in Ionic 3Just a heads-up

I need to capture the back button event before it triggers. Once the listener is activated, the back signal has already been sent. This is my approach so far: document.addEventListener("backbutton", () => { console.log("[WARN] Back button pres ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

How can I simulate a callback function that was not tested?

Currently experimenting with the method below: startScriptLoad(): void { const documentDefaultView = this.getDocumentDefaultView(); if (documentDefaultView) { const twitterData: ICourseContentElementEmbedTweetWidgetData = this.getTwitterWid ...

Steps to resolve the issue of 'type is not assignable to any' while working with a member

I'm facing an issue with a code snippet like the one below: interface IFoo { bar: string; baz: number; } function f(foo: IFoo, name: 'bar' | 'baz', val: any) { foo[name] = val; // <<< error: Type 'any' i ...

Tips for dynamically accessing object properties in TypeScript

I've been going through the process of converting existing Node.js projects to TypeScript. As part of this, I am utilizing the http-status package (https://www.npmjs.com/package/http-status) for handling HTTP status codes. While trying to pass varia ...

TypeScript version 3.7 has implemented a new feature where it will now display errors for each individual invalid prop instead of grouping them together as it

Scenario using TypeScript 3.5.3 https://i.stack.imgur.com/wykd6.png link to interactive playground - TS 3.5.3 demo running successfully Example with TypeScript 3.7.2 https://i.stack.imgur.com/BPckB.png link to demo - TS 3.7.2 demo not functioning correctl ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

The type Observable<any> cannot be assigned to Observable<any> type

I am currently working with angular 5 and ionic 3. I have defined an interface: export interface IAny { getDataSource: Observable<any>; } Components that implement this interface must have the following method: getDataSource () { return ...

What is the process for defining a default value for a template-driven form input in Angular 2?

I have a simple input element in my form that requires a default initial value to be set. <input type="number" name="interest_rate" [(ngModel)]="interest_rate"> In my code, I included this.form.controls['interest_rate'].patchValue(this.a ...

Guide on showcasing file content in a modal popup within a Kendo Grid

Currently, I am facing an issue with displaying the content of a JSON file within a modal window. All I can manage to do is display the file name as a link, but what I really want is to display the actual content of the file. Do you have any ideas on how ...

Reset the select boxes when a button is clicked

I'm currently utilizing Devextreme within my Angular application, and I have three dx-selectbox elements in the component. I am attempting to clear all three dropdown selections when clicking a "clear" button. Unfortunately, I am unable to find a way ...