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エラーが発生します。これら 2 つのコンポーネントを正しく接続するにはどうすればよいですか? 独自のビューでサブコンポーネントを定義するのは適切な方法ですか?

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;
}

プランク

于 2015-05-13T23:45:00.003 に答える