简体   繁体   中英

Angular @Input of type Observable

Is it bad practice to pass in a component's @Input an observable ?

For example: The template of the parent will have

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

and the ProfileEditComponent will have a variable like this:

@Input items$: Observable<ProfileItem[]>

And use the | async pipe to unrwap the values of the observable in the template of the ProfileEditComponent

For async pipe this is good solution, but be aware of change detection mechanism. Because from angular point of view [items] bounded property does not change, if your change detection strategy will be set to onPush , your view might not be refreshed accordingly. Then, you will need to manually subscribe to this input observable and on each change trigger change detection by yourself.

I think this is not good practice. Angular provides you an async pipe which is exactly what you want here.

When using async pipe:

  • less code is generated since you do not need to subscribe to the observable first.

  • The component does not need to know about Observable class and is more stupid like this

So I think this:

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


@Input items: ProfileItem[]

Is cleaner and better than this:

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


@Input items: Observable<ProfileItem[]>`

Just my guesses, I am not a specialist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM