Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How would you subscribe multiple variables?

Using Angular 2, I receive JSON data from a service. Something like this:

{
    "customerName": "foo",
    "customerAddress": "123 Somewhere",
    "products": 
    [
        {
            "productName": "bar",
            "productNumber": 123 
        },
        {
            "productName": "baz",
            "productNumber": 456             
        }
    ]
}

In my component I subscribe to the service to get populate customerData.

private _getData() {
    this._myService
        .getData()
        .subscribe(
            customerData => this.customerData = customerData,
            error => this.errorMessage = error
        );
}

This code works correctly.

In the JSON dump there are two data "groupings", the customer data and the product data, the latter in the array. Ideally I'd like to populate the product data separately. Something like this:

        .subscribe(
            customerData => this.customerData = customerData,
            productData => this.productData = customerData.products
            error => this.errorMessage = error
        );

Is this possible, and if so how would I code the subscription?

like image 984
ebakunin Avatar asked Dec 25 '22 06:12

ebakunin


1 Answers

You could write subscribe like

    subscribe(
        customerData => 
        { 
         this.customerData = customerData;
         this.productData =customerData.products;
        },
        error => this.errorMessage = error
    );

Or

   subscribe(
        function(customerData)
        { 
         this.customerData = customerData;
         this.productData =customerData.products;
        },
        error => this.errorMessage = error
    );
like image 77
Antonio Avatar answered Dec 28 '22 10:12

Antonio