简体   繁体   中英

Angular 2 fill variable with return JSON info from HTTP Request

I'm pretty new on Angular2, and I'm trying to obtain the key/value pair from a JSON file returned by a Http request. I want to store them on the objectResource property so I can retrieve them on the template.

This is my component.ts :

export class ResourceDetailComponent implements OnInit {

    objectResource: any = Array();
    id:any;
    sub:any;

    constructor(private contentService: ContentService, private route: ActivatedRoute) {

        this.sub = this.route.params.subscribe(params => {
            this.id = +params['id'];
        });

        this.getResource(this.id);
     }

    ngOnInit(){}

    private getResource(id:number) {
        return this.contentService.getSpecificResource(id).then(res => this.objectResource.push(res));
    }


}

and this is mi service.ts:

public getSpecificResource(id:number) {
        return this.http.get(`http://resources.dev/v1/resources/show/${id}`)
        .toPromise()
        .then(res => res.json());
    }

when I do console.log on res I obtain this log, which mean the service is doing the request as expected:

Object {
    id: 1, 
    name: "quisquam", 
    image: "http://lorempixel.com/480/480/?88330", 
    description: "Consequuntur quo provident alias aut rerum.", 
    author: "Marc Mann Sr."
}

I've tried to retrieve these values on the template using {{objectResource.name}} but isn't working, and I don't know how can I access this values from the template.

objectResource is an array not an object. Just do it like

{{objectResource[0].name}}

Please consider add checking before printing it because angular will throw an error if the array is undefined

Try using subscribe which will auto update the object when value is resolved.

component.ts

private getResource(id:number) {
    return this.contentService.getSpecificResource(id)
        .subscribe(res => this.objectResource = res,
                   err => console.log(err));

template.html

 <div *ngIf='objectResource'>
    {{objectResource.name}}
 </div>

OR

Use async pipe that can receive a Promise or Observable as input and subscribe to the input automatically, eventually returning the emitted value(s).

component.ts

private getResource(id:number) {
   this.objectResource = this.contentService.getSpecificResource(id);
   return this.objectResource;
}        

template.html

 <div *ngIf='objectResource | async'>
    {{objectResource.name}}
 </div>

When the template is loaded, the objectResource might not be ready. Try to put ? from your objectResource like this

 {{objectResource?.name}}

or insert a div element like this

  <div *ngIf='objectResource'>
    {{objectResource.name}}
  </div>

Hope this helps.

Angular's change detection is not triggered when an object is mutated (eg an element is added to your array). See Triggering Angular2 change detection manually . Specifically this solution https://stackoverflow.com/a/42695581/3103979

First of all make this change

export class ResourceDetailComponent implements OnInit {

    objectResource: Array<any> = [];
    ..........
}

If there will be an array of multiple data.

<div *ngFor='let data of objectResource'>
    <div> id : {{data.id}} </div>
    <div> name : {{data.name}} </div>
    <div> description : {{data.description}} </div>
    .....
</div>

This will show data if there is any data inside " objectResource "

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