简体   繁体   中英

get key/value pair from json response object in angular 2 typescript

 return this._http.post(apiUrl, model)
            .map((res: Response) => {
                console.log(res.json());
                let user = res.json();
               //let user = Object.keys(res.json());   <-- only gives keys not values

                if (user) {
                    localStorage.setItem('currentUser', JSON.stringify(user));
            }
        })

this is my post method ...

this is console output ...

Object {Id: 101, UserName: "appatel", FirstName: "aarsh", LastName: "patel", Password: "aarsh"…}
Email: "aarshpatel@gmail.com"
FirstName: "aarsh"
Gender: "Male  "
Id: 101
LastName: "patel"
Password: "aarsh"
UserName: "appatel"

I want to set username in local storage .. How can I do that ??

Just access the property UserName,

if (user) {
     localStorage.setItem('currentUser', JSON.stringify(user.UserName));
}

Set Data :

let user = res.json();
if (user) {
    localStorage.setItem('currentUser', JSON.stringify(user));
}

Fetch data :

if(localStorage.getItem('currentUser')) {
    let user_data = JSON.parse(localStorage.getItem('currentUser'));
    console.log(user_data);
    console.log(user_data.UserName);
}

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