Passing value between two components in angular2-meteor project

247 Views Asked by At

I am using angular2-meteor.

When I try to pass a value between two components (when the value change in the first component, create an event in second component and use this new value), I have two ways right now:

  1. One way is meteor way: using this.autorun and Session.get.
  2. Another way is angular2 way: using Injectable service with EventEmitter.

Which way should be prior? Or is there any other better way? Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

Now I used angular2-meteor a while.

Although the angular2-meteor tutorial has no example so far about using or choosing Angular 2 service or Meteor Session.

But I feel angular 2 takes the lead in the front end, while meteor makes reactivity easier and also handle all back end things.

So I went with angular2 way using service to share between components. And service is very powerful like @todd-w-crone said.

If anyone has better answer, I will switch to accept that one.

0
On

I find it practical to create a new service called App.states.ts which is accessed globally and mimics Session (get / set). I commonly import this service to all necessary components to get or set new value such as User.status, company.profile, lastProduct, etc.

Since this service is @injectable it can also make use of other services, in case a value hasn't been set already. This allows me to ask for a variable in a component appState.getLastModifiedItem(), then in app.states.ts I'll write this function to pass this.modifiedItem or either:

  • Request another service item.service.ts to fetch data
  • Call another function with itemCollection.findOne({...}) and return such value.

You can configure Mongo queries as you want and either store static data in appState or keep subscription items in appState.

Do take into consideration that all subscriptions handled by an @injectable within a component are imported by such component. Be wary of conflicting subscriptions between components/services.