代码之家  ›  专栏  ›  技术社区  ›  Ivelin Matev

角度@可观测类型的输入

  •  3
  • Ivelin Matev  · 技术社区  · 7 年前

    将组件的@input传递给observable是否是一种坏做法?

    例如: 父模板将具有

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

    profileEditComponent将有一个这样的变量:

    @Input items$: Observable<ProfileItem[]>
    

    并使用异步管道在模板中展开可观察的值。 配置文件编辑器组件的

    2 回复  |  直到 7 年前
        1
  •  2
  •   Silvan Bregy    7 年前

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

    使用时 异步的 管道:

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

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

    所以我认为:

    <profile-edit [items]="profileFacade.items$ | async">
    
    
    @Input items: ProfileItem[]
    

    比这更干净更好:

    <profile-edit [items]="profileFacade.items$">`
    
    
    @Input items: Observable<ProfileItem[]>`
    

    据我猜测,我不是专家。

        2
  •  2
  •   Tomas    7 年前

    为了 async 管道这是很好的解决方案,但要注意变化检测机制。因为从角度来看 [items] 如果更改检测策略设置为 onPush ,您的视图可能不会相应地刷新。然后,您将需要手动订阅这个可观察的输入,并在每次更改时自己触发更改检测。