Pass values between components Angular 2 - Not Par

2019-09-19 11:05发布

问题:

Just learning Angular and would like some design architecture advice.

If I have a search component that needs to feed a summary component with the results, without them necessarily being parent/child, what's the best architectural approach to doing this?

Thanks,

回答1:

If your component isn't parent / children, use service for to share your data. I thinks is the best practice.



回答2:

The best approach would be to use the parent-child relation.

But if you don't want to, there are several ways, including :

  • Using a shared service in a shared module
  • using a shared file (like environment.ts) to share your values
  • use the built-in methods (for instance, localStorage) of browsers.

I think that the ranking goes something around

Parent/Child > Service > Shared file > Common methods


回答3:

There are few approaches:

  • Using Services(Most Recommended).
  • Using Behavior Subjects from RxJS library.
  • Using browser storage(session/local) but least recommended as prone to data security.