How to pass a JSON to an Object?

0

Good Day

My problems is I have this JSON

{"status":"success","code":200,"data":[{"ID":70}]}

That I got it from this function to make it clearer:

this._service.getDato().subscribe(
        result =>   this.datosParaEditar(result.data)
        )

When I get result.data I want to save it in an object like this

public data: IdModelo; // que es el objeto

datosParaEditar(result){
    this.data = new IdModelo(result.ID);
}

but when printing it I get that result.ID is null and empty, and when printing by console only results, the JSON is printed [{"ID": 70}], I would like to know how I can save this data in an Object .

    
asked by DaVid Roa 12.10.2017 в 22:32
source

2 answers

2

If you look carefully "data":[{"ID":70}] saves a array de objetos for which to access the value you want you must first enter the position 0 of that array and there if you can access the properties of that object. / p>     

answered by 12.10.2017 / 22:50
source
2

There are several ways, in the first instance you could use JSON.parse() when you subscribe to the Observable that your service returns, however that is not the best, since Angular provides a way to pair the JSON directly when you define your service if you use the HttpModule module, available in @angular/http . You only need map ear the answer of your service and occupy the .json() method, for example:

import { Http } from '@angular/http'
@Injectable()
export class fooService{
  constructor( private http: Http ) {}

  getDato() {
    return this.http.get('endpoint').map(res => res.json())
  }
}

From Angular 4.3 a new HTTP module called HttpClientModule was introduced, and it is imported from @angular/common/http , and with this version it is no longer necessary map ear such answer, therefore your service would look something like this:

import { HttpClient } from '@angular/common/http'
@Injectable()
export class fooService{
  constructor( private http: HttpClient ) {}

  getDato() {
    return this.http.get('endpoint');
  }
}

In summary: If you use the old http module, you must use .map() and return res.json() , if you use the new module, the answer already comes as an object and it is not necessary to convert the JSON.

    
answered by 12.10.2017 в 22:49