Tips for sending multiple values to an Angular 5 observable

As I continue my journey of learning Angular, I am encountering a challenge that has me stuck. In one component, I have three values that I need to pass to another component. While I have a basic grasp of observables and subscriptions, I have only worked with passing 1 parameter in the past. Now, I find myself wanting to broadcast 3 values simultaneously.

Let's take a look at my shopping cart code:

additem(itemText){
  this.cart.push(itemText);
  this.itemscount = this.cart.length;
  this._data.changeCart(this.cart);
}

Every time I click on a product, the above function is triggered, sending the 'cart' array to an observable where it is then broadcasted.

export class DataService {

    private cart = new BehaviorSubject<any>([]);
    cast = this.cart.asObservable();

    constructor() { }

    changeCart(item_param) {
        this.cart.next(item_param);
        //console.log(this.cart);
    }

}

Now I am faced with the dilemma of how to pass 3 values through the observable. I have come across the idea of packaging all three values into an array and passing that along, but I am unsure about how to store multiple values within a single array in Angular.

I would greatly appreciate any assistance or guidance on this matter. Thank you!

Answer №1

To create an object in JavaScript, you simply follow these steps:

let a = 5;
let b = 'sss';
let c = new Date();

let objToPass = { a: a, b: b, c: c };

Afterwards, you can retrieve the object properties using objToPass.a, objToPass.b, and so on.

This method is commonly used for constructing JS objects.

Answer №2

Learn how to create an object and utilize it for multiple purposes

export class DataHandler {

    private dataObject = new BehaviorSubject<Object>({});
    dataObjectInfo = this.dataObject.asObservable();

    constructor() { }

    modifyData(dataObject) {
        this.dataObject.next(dataObject);
    }
}

Begin by retrieving the value from BehaviorSubject

this.handler.dataObjectInfo.subscribe(dataObject => {
   if(dataObject) this.dataObject = dataObject; 
});
this.handler.modifyData({//insert full object details here});

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

Utilizing IonPage and DeepLinkMetadataType in Ionic 3 for tab navigation: Eliminating the need for tab-0

One of the pages on my site contains tabs that are only loaded when clicked: explore.html <ion-tabs> <ion-tab [root]="tab1Root" [tabTitle]="hotTitle" tabIcon="flame"></ion-tab> <ion-tab [root]="tab2Root" [tabTitle]="searchTitle ...

Enhancing Mongoose promises with Bluebird in a TypeScript environment

Currently, I am working on a project that involves developing an application using nodejs/typescript and a mongodb database. In order to interact with the database, I have implemented mongoose as my query interface. Recently, I came across an informative ...

I am experiencing issues with utilizing `await` within an `async` function in TypeScript

The code below is functioning without any issues when making a superagent call. However, the each callbacks are being blocked in the program and I am encountering an empty array at the end of its execution. If anyone has suggestions on how to resolve this ...

Navigating in Angular 2: Ways to route to a different page while keeping the HTML hidden from the app.component.html file on the new page

Just recently, I encountered a minor issue. I already have a good understanding of how to navigate between different pages, but there's one thing that bothers me - each time I switch to a new page, the app.component.html always appears at the top of t ...

Angular2 and Bootstrap 4 table combined to create an extra column

Here is the HTML code I used to create a table: <table class="table table-bordered"> <thead> <tr> <th *ngFor="let th of tableHeaders"> {{th}} <th> </tr> ...

What can I do to enhance the efficiency of this function in React?

Issue I am facing a problem with two inputs that trigger an event to update the quantity of a specific product. However, I noticed that entering a number quickly tends to slow down the process, especially when dealing with multiple products. It takes abo ...

Is there a way to determine the most recent Typescript target compatibility for every Node version?

When using any version of Node, how can I identify the appropriate Typescript Compiler Option for target that offers the most functionality? I want to eliminate any guesswork. Specify the ECMAScript target version as: "ES3" (default), "ES5", "ES6"/"ES20 ...

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

Currently, my goal is to upload a photo using Cloudinary's post API without relying on the Cloudinary SDK

Recently, I have been exploring the integration of cloudinary with Angular. In my quest to upload an image to cloudinary without using the SDK, I came across the option to do so via the post API. However, my attempts with the following code snippet were un ...

Create a method that specifies the signature to include a function as a parameter

I am interested in defining a Type Definition that adheres to this function: var a : MyInterface = function(func : <T>(t: T) => number) { console.log("do Nothing"); return func(123) + " someString"; } My goal is to create an Interface that a ...

Utilizing the backtick operator for string interpolation allows for dynamic value insertion

Greetings! Currently, I am delving into the world of Angular 2 and have stumbled upon some interesting discoveries. To enhance my knowledge of TypeScript, I decided to utilize the ScratchJS extension on the Chrome browser. During this exploration, I experi ...

The continual request for importing React on NextJS and React 17 applications by VSCode remains persistent

I've disabled specific rules in my eslintrc.json configuration file: https://i.sstatic.net/n2hR5.png However, when I use the shortcut ctrl+. to import a component from another file, Visual Studio Code still suggests importing React. https://i.sstat ...

Creating a versatile transformer function for TypeScript subtypes without relying on type assertions

Currently, I am diving into the world of functional programming using TypeScript for a personal project. My focus lies on harnessing the power of higher-order functions and the pipe function to craft expressive transformers. While experimenting with these ...

How can I prevent other input fields from being enabled once the value "matched" is received in the first input field using Angular?

When working with a template driven form, I encountered a scenario where I needed to disable other input fields if the value entered matched a specific string. For example, if the first input field's value is "sample", then the other input field shoul ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Angular Kendo UI offers the ability to customize the way grid columns are sorted

I'm currently working on a Kendo Grid (UI for Jquery) where I have implemented a custom sort method for a specific column based on my customers' requirements. field: "daysLeft", title: "Accessible", width: 130, sortable: { compare: function (a ...

the redirection fails to initiate following the button press

I've encountered an issue similar to one discussed on stackoverflow, but I haven't been able to resolve it. I'm currently on the locking page and when a user clicks on a button, they should be redirected to the select-portfolio page. Howev ...

An issue occurred: Cannot retrieve the 'slice' property from an undefined source at SafeSubscriber while transitioning to the next step

While attempting to utilize the map operator, an ERROR TypeError is displayed in the console saying: "Cannot read property 'slice' of undefined" at SafeSubscriber._next. How can I resolve this issue? https://i.sstatic.net/aROag.png I am using t ...

Dialog in Angular Material refuses to close even after calling the dialog.close() function

I've been struggling with this issue for a while, hoping someone can assist. In my Angular project, I have a login component with a dialog that opens a new popup window. Upon successful login, this window closes and triggers the following function: l ...

Create an array containing the data returned from the Observable<{string, number, string}[]> stream

Currently I am working on creating an Angular 9 app, and I need to return an array with my response. Within the service class, I have a method like this: getReport(startDate: string, endDate: string) { return this.http.get<ReportReport>( ...