dev
dev

Reputation: 565

How to pass multiple values to angular 5 observable?

I am learning angular day by day but I am stuck on a problem. I have 3 values in one component and I need to pass them to another component. I have basic understanding of observable and subscription but I have done it with 1 parameter. Now I want to broadcast 3 values

Here is my code of shopping cart.

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

When I click on a product this function calls and it sends cart array to observable and there I broadcast the cart array

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 need to pass 3 values to observable and I am confuse how to do it because I have read that we can pass only one value to observable. I had one idea to wrap all values in an array and pass that array but I search on this but could not find that how to store multiple values in single array in angular.

Any help would be highly appreciated.Thanks

Upvotes: 2

Views: 9885

Answers (2)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

You can just make an object like so:

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

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

Later, you can access object properties like objToPass.a, objToPass.b, etc.

That's the standard way of constructing JS objects.

Upvotes: 6

Rakesh Chand
Rakesh Chand

Reputation: 3113

Here's how you can make it a object and use it for multiple values

export class DataService {

    private cartObject = new BehaviorSubject<Object>({});
    cartObjectInfo = this.cartObject.asObservable();

    constructor() { }

    changeCart(cartObject) {
        this.cartObject.next(cartObject);
    }
}

First is get the value in BehaviourSubject

this.data.cartObjectInfo.subscribe(cartObject => {
   if(cartObject) this.cartObject = cartObject; 
});
this.data.changeCart({//make the full object here});

Upvotes: 1

Related Questions