Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting key and value from JSON with angular2

I am looking for best solution how to work with JSON in my angular2 app.

My JSON is:

{
    "rightUpperLogoId": {
        "id": 100000,
        "value": ""
    },
    "navbarBackgroundColorIdCss": {
        "id": 100001,
        "value": ""
    },
    "backgroundColorIdCss": {
        "id": 100002,
        "value": ""
    },
    "translationIdFrom": {
        "value": "90000"
    },
    "translationIdTo": {
        "value": "90055"
    }
}

This JSON is something like configuration file for UI of app. In my application, I want to get id from rightUpperLogoId, it is 100000. With this id I need to do GET task on my backend REST api and the returned value I would like to set to value. Thank you

like image 1000
Loutocký Avatar asked Aug 22 '26 13:08

Loutocký


1 Answers

You could leverage Rx operators like the flatMap one with Observable.forkJoin / Observable.of.

Here is a sample:

this.http.get('config.json')
       .map(res => res.json())
       .flatMap(config => {
         return Observable.forkJoin(
             Observable.of(config),
             // For example for the request. You can build the
             // request like you want
             this.http.get(
               `http://.../${config.rightUpperLogoId.id}`)
         );
       })
       .map(res => {
         let config = res[0];
         let rightUpperLogoIdValue = res[1].json();

         config.rightUpperLogoId.value = rightUpperLogoIdValue;

         return config;
       })
       .subcribe(config => {
         // handle the config object
       }); 

This article could give you more hints (section "Aggregating data"):

  • http://restlet.com/blog/2016/04/12/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-2/
like image 67
Thierry Templier Avatar answered Aug 25 '26 20:08

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!