在Angular2中使用点访问JSON字段

时间:2017-04-03 08:36:38

标签: json angular

作为angular2的新手,我想知道如何访问带有点的JSON字段。

JSON文件

 [  
   {  
      "s.no":0,
      "amt.pledged":15823,
      "blurb":"'Catalysts, Explorers & Secret Keepers: Women of Science Fiction' is a take-home exhibit & anthology by the Museum of Science Fiction.",
      "by":"Museum of Science Fiction",
      "country":"US",
      "currency":"usd",
      "end.time":"2016-11-01T23:59:00-04:00",
      "location":"Washington, DC",
      "percentage.funded":186,
      "num.backers":"219382",
      "state":"DC",
      "title":"Catalysts, Explorers & Secret Keepers: Women of SF",
      "type":"Town",
      "url":"/projects/1608905146/catalysts-explorers-and-secret-keepers-women-of-sf?ref=discovery"
   },
   {  
      "s.no":1,
      "amt.pledged":6859,
      "blurb":"A unique handmade picture book for kids & art lovers about a nervous monster who finds his courage with the help of a brave little girl",
      "by":"Tyrone Wells & Broken Eagle, LLC",
      "country":"US",
      "currency":"usd",
      "end.time":"2016-11-25T01:13:33-05:00",
      "location":"Portland, OR",
      "percentage.funded":8,
      "num.backers":"154926",
      "state":"OR",
      "title":"The Whatamagump (a hand-crafted story picture book)",
      "type":"Town",
      "url":"/projects/thewhatamagump/the-whatamagump-a-hand-crafted-story-picture-book?ref=discovery"
   }]

user.component.ts

import { Component } from '@angular/core';
import {PostsService} from '../services/posts.service';



@Component({
    moduleId:module.id,
  selector: 'user',
  templateUrl:'user.component.html',

    providers:[PostsService]  

}) 
export class UserComponent  { 

    posts:Post[];


    constructor(private postsService: PostsService){


    this.postsService.getPosts().subscribe(posts => {
        this.posts=posts;
            });
    }



    }


interface Post{

      title:string;
      by:string;
      blurb:string;
      location:string;
      state:string;
      country:string;
      currency:string;      
      type:string;
      url:string; 


}

当我尝试在上面的界面帖子中添加amt.pledged:number;时,我收到错误&#34;未使用的标签&#34;。我无法访问HTML文件中带点(。)的字段。< / p>

user.component.html

<div class="container">


    <h3>Projects</h3>
    <div *ngFor="let post of posts" class="col-sm-4 a">
        <h3><a href="{{post.url}}" target="_blank">{{post.title}}</a></h3>
        <p>By {{post.by}}</p>
        <p>{{post.blurb}}</p>

        <p>{{post.location}}</p>

        <button class="btn btn-success"><a href="/about" class="b">Know more!</a></button>

    </div>


    </div>

谢谢!

1 个答案:

答案 0 :(得分:2)

你可以用这样的点

声明一个变量
interface Post{
       title:string;
       "amt.pledged": string;
}

为了访问html文件中的属性,您可以使用括号表示法

object['amt.pledged']