Angular 2填充变量,返回来自HTTP Request

时间:2017-03-29 00:55:32

标签: json angular

我在Angular2上很新,我试图从Http请求返回的JSON文件中获取键/值对。我想将它们存储在objectResource属性上,以便我可以在模板上检索它们。

这是我的 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));
    }


}

这是mi service.ts:

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

当我对res console.log执行此操作时,我获取此日志,这意味着该服务正在按预期执行请求:

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

我尝试使用{{objectResource.name}}在模板上检索这些值但是不起作用,而且我不知道如何从模板中访问此值。

5 个答案:

答案 0 :(得分:1)

objectResource是一个数组而不是一个对象。就像

一样
{{objectResource[0].name}}

请在打印前考虑添加检查,因为如果数组未定义,angular会抛出错误

答案 1 :(得分:1)

尝试使用subscribe,它会在解析值时自动更新对象。

<强> 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>

使用可以接收Promise或Observable的async管道作为输入并自动订阅输入,最终返回发出的值。

<强> component.ts

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

<强> template.html

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

答案 2 :(得分:0)

加载模板时,objectResource可能没有准备好。试着放?来自你的objectResource就像这样

 {{objectResource?.name}}

或插入像这样的div元素

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

希望这有帮助。

答案 3 :(得分:0)

当一个对象发生变异时(例如,一个元素被添加到你的数组中),不会触发Angular的变化检测。见Triggering Angular2 change detection manually。特别是此解决方案https://stackoverflow.com/a/42695581/3103979

答案 4 :(得分:0)

首先进行此更改

export class ResourceDetailComponent implements OnInit {

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

如果有多个数据的数组。

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

如果“objectResource

中有任何数据,这将显示数据