简体   繁体   中英

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

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"):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM