2

我有一个从示例 API 获取数据的简单应用程序。在将指令定义为组件时试图找出问题所在:

app.ts

import {Component, View, bootstrap, For} from 'angular2/angular2';
import {ArticlesSvc} from 'services/articlesSvc';
import {ArticleItem} from 'directives/ArticleItem';

@Component({
  selector: 'main-app',
  injectables: [ArticlesSvc]
})

@View({
  template: `<p *for="#post of posts">{{ post.title }} <article-item [body]="post.body"></article-item></p>`,
  directives: [For,ArticleItem]
})

class MainComponent {
  posts: Array<string>;

  constructor(articlesSvc: ArticlesSvc) {
    this.posts = [];

    articlesSvc.get('http://jsonplaceholder.typicode.com/posts').then((data) => {
       this.posts = data;
    });

  }

}

bootstrap(MainComponent);

这是ArticleItem组件:

import {Component, View} from 'angular2/angular2';

@Component({
  selector: 'article-item',
  properties: ['body']
})

@View({
  template: `<p>{{ body }}</p>`
})

export class ArticleItem {
    body:string;
}

出于某种原因,它给了我Unexpected number错误。如何正确连接这两个组件?它是用自己的视图定义子组件的正确方法吗?

4

1 回答 1

2

我认为问题在于当您尝试绑定子组件中的属性时,您设置的是数组而不是对象。因此,当它尝试为绑定属性创建设置器时,它会遍历为键iterableChanges提供的值() ,但在您的情况下,它是一个数组而不是对象,因此为索引创建一个设置器,例如:“0”失败.propertiesComponent

即尝试:

@Component({
  selector: 'article-item',
  properties: {body: 'body'} //<-- Here
})

另一个注意事项,可能是一个错字(与此示例无关):您的主要组件类的post属性被声明为类型Array<string>而不是可能Array<Post>(只是为了类型安全:)):

interface Post extends ArticleItem{//or even class Post
    title: string;
}

PLNKR

于 2015-05-13T23:45:00.003 回答