如何将Observable属性传递给Angular2中的组件?

时间:2016-12-07 03:23:45

标签: angular data-binding observable

尝试将Observable对象的属性传递给这样的组件:

<bookmark [type]="'store'" [targetId]="(store | async)?.id" [endDate]="99999999999999"></bookmark>

但是targetId总是未定义的。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

你做得对,但我猜你正面临另一个问题..

让我在这里演示一下:https://plnkr.co/edit/AE67JyXZ5hg6A1ahrm7E?p=preview

如果它是&#34;正常&#34; observable,只有在视图启动后触发事件时才会更新视图!

如果之前有事件,则不会显示!

因此你应该使用BehaviorSubject,它将&#34;缓冲&#34;最后一个值。

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

      <br />
      without timeout: {{ (testWoTimeout | async)?.any }} <!-- will not be shown -->

      <br />
      with timeout: {{ (test | async)?.any }} <!-- will be shown cause of that timeout -->

      <br />
      behavior subject: {{ (behaviorTest | async)?.any }} <!-- will be shown cause of that BehaviorSubject -->
    </div>
  `,
})
export class App {
  name:string;

  test = new Subject();
  testWoTimeout = new Subject();
  behaviorTest = new BehaviorSubject({ any: 'default' });

  constructor() {
    this.name = 'Angular2'
  }

  ngOnInit() {

    this.testWoTimeout.next({ any: 'prop' }); // this will not be shown, cause its fired before the view was initiated!

    this.behaviorTest.next({ any: 'prop' });

    setTimeout(() => {
      this.test.next({ any: 'prop' });
    }, 250);
  }
}