Observable 类型的 Angular @Input

Ive*_*tev 6 observable typescript angular

将组件的 @Input 传入 observable 是不好的做法吗?

例如:父级的模板将有

<profile-edit [items$]="profileFacade.items$">
Run Code Online (Sandbox Code Playgroud)

并且 ProfileEditComponent 将有一个像这样的变量:

@Input items$: Observable<ProfileItem[]>
Run Code Online (Sandbox Code Playgroud)

并使用 | 异步管道解开 ProfileEditComponent 模板中可观察值的值

Sil*_*egy 6

我认为这不是一个好的做法。Angular 为您提供了一个async管道,这正是您在这里想要的。

使用async管道时:

  • 生成的代码更少,因为您不需要先订阅 observable。

  • 组件不需要知道Observable类,像这样更蠢

所以我认为:

<profile-edit [items]="profileFacade.items$ | async">


@Input items: ProfileItem[]
Run Code Online (Sandbox Code Playgroud)

比这更干净更好:

<profile-edit [items]="profileFacade.items$">`


@Input items: Observable<ProfileItem[]>`
Run Code Online (Sandbox Code Playgroud)

只是我的猜测,我不是专家。

  • 我不同意。可观察的输入并不是一个坏习惯。此外,它允许将changeDetectionStrattegy设置为OnPush,这将产生优化的组件,并且无需实现OnChanges接口来处理更改。 (3认同)