我有一个简单的应用程序从示例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
错误。如何正确连接这两个组件?它是用自己的视图定义子组件的正确方法吗?
答案 0 :(得分:2)
我认为问题是当您尝试绑定子组件中的属性时,您正在设置数组而不是对象。因此,当它尝试为绑定属性创建setter时,它会迭代为properties
的{{1}}键提供的值(Component
),但在您的情况下,它是一个数组而不是对象因此为索引创建一个setter,例如:“0”失败。
即尝试:
@Component({
selector: 'article-item',
properties: {body: 'body'} //<-- Here
})
另一个注释,可能是一个拼写错误(与此示例无关):您的主要组件类“post
属性声明为Array<string>
类型,而不是Array<Post>
(只是为了类型安全:)):
interface Post extends ArticleItem{//or even class Post
title: string;
}
<强> Plnkr 强>