Accessing data from an Angular array

Asked

Viewed 242 times

1

I’m trying to access a data ID that my API responds that it is inside an array:

{
  "name": <name>
  "email": <email>
  "token": <token>
  "message": 'Token válido.'
  "subscriptions": [
   {
     "id": "<id>", // preciso pegar a id
     "startdate": "<startdate>",
     "enddate": "<enddate>",
     "active": "<active>",
     "course": "<course>"
   }]
}

I’m saving in the localStorage cell phone as follows:

ngOnInit() {
    this.authloginService.getCourses(this.token, this.course)
    .then((result)=> {         
      localStorage.setItem('subscriptions(id)', result['subscriptions'])
      console.log(result['subscriptions']);      
     });
  }

But the console.log me answers the entire array of subscriptions;

Here the service:

getCourses(token:string, course:string){    
    token = encodeURIComponent (localStorage.getItem('token'));
    course = encodeURIComponent (course);     
    var cursos = `token=${token}&course=${course}`;    
    return this.http.post('https://minhaapi.com.br/api/subscriptions', 
              cursos , {headers: this.headers}).toPromise();

}

I’m missing in the localStorage or in the service?

1 answer

1


I think you’re missing storage time:

It can be done like this:

localStorage.setItem('subscriptions(id)', result['subscriptions'][0]['id']);

where in that case it is stored id of the return in localStorage and to recover the value again:

const id = localStorage.getItem('subscriptions(id)');

is the simplest solution.

Or could be done so save all the result using the JSON in text with JSON.stringify():

localStorage.setItem('subscriptions(id)', JSON.stringify(result));

and then in its id taking the generated and transforming text JSON with the command JSON.parse():

const json = JSON.parse(localStorage.getItem('subscriptions(id)'));

and then use that way to also recover the id (remember that can recover all values, I am being specific the question)

const id = json.subscriptions[0].id;

const json = {
  "name": "<name>",
  "email": "<email>",
  "token": "<token>",
  "message": "Token válido.",
  "subscriptions": [
     {
        "id": "1", 
        "startdate": "<startdate>",
        "enddate": "<enddate>",
        "active": "<active>",
        "course": "<course>"
      }
   ]
};

console.log(json.subscriptions[0].id); // ou
console.log(json['subscriptions'][0]['id']);

  • 1

    That’s right, thank you very much !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.