将数组值输出到模板

时间:2016-08-27 11:37:09

标签: json angular angular-template

我目前正在学习Angular 2,并且对如何将服务返回的数据输出到我的模板感到困惑。

我的API响应:

{
  "site": {
    "success": true,
    "title": "foo",
    "description": "bar"
  }
}

我的服务:

 import { Injectable } from '@angular/core';
 import  {HTTP_PROVIDERS, Http, Response, Headers, RequestOptions } from "@angular/http";
 import { Observable } from 'rxjs/Rx';


 @Injectable()
 export class ContentService {
     constructor(private _http:Http) {}

     getContent() {
         return this._http.get('http://localhost:8080/api/foobar-endpoint/')
             .map((res:Response) => res.json())
     }

 }

我的组件:

import { Component, OnInit } from '@angular/core';
import { ContentService } from "../../services/content/content.service";

const template = require('./home.jade');
const styles = require('./home.sass');

@Component({
    selector: 'home',
    templateUrl: template,
    styleUrls: [styles]
})

export class HomeComponent implements OnInit {

    public foo = {}

    constructor(private _contentService: ContentService) {}

    ngOnInit() {
        this.getContent();
    }

    getContent() {
        this._contentService.getContent()
            .subscribe(
                data => {this.foo = data},
                err => { console.log(err) },
                () => console.log()
            );
    }

}

我的模板:

pre
    p {{ foo.site.title }}

如果我将{{ foo | json }}放在我的模板中,我可以看到JSON格式的返回值,但是当我尝试输出单个值时,例如title,我会得到未定义的错误。

如何访问返回的值?

1 个答案:

答案 0 :(得分:0)

我认为你唯一缺少的是?。基本上问题是,当组件实例化时,foo属性没有site参数,因此angular会抛出错误。

所以你能做的就是:

{{foo.site?.title}}

或者这个:

<p *ngIf="foo.site">{{foo.site.title}}</p>

这样,角度不会尝试在有网站之前绑定标题。