If I pass a service into my main.ts I can access it anywhere without having to call a new provider within my child components. In that service, I have variables that are changing.
Would it be better to send those variables to each child component, grandchild component, ..etc or just call the service in my component to get those variables when I need them?
If I understood the question correctly, we might also need to think of 2 diff aspects associated with these decisions.
@Input/@Output - Helps make your components independent and Not Tied to any particular service. Assuming it is a pure component, that relies completely on the Input received to produce Output; which is definitive, easily testable, very loosely coupled to the other portions of the application; hence high re-usability is encouraged and easily possible.
Changing Data of Variables - UI State Management is of supreme importance and is probably very core for Angular 2 apps, to my understanding till date. ngrx/store is the Redux in Reactive world and does this well. In this way we can keep data transformations predictive, testable and the data can be referred back anytime by any service/container components as needed and can be passed in the component chain.
So, I according to me shared service is a good solution with Rxjs library. You can make service singleton by injecting it into bootstrap function.
The @Input
and @Output
decorators are mainly to share data from parent-child and child-parent respectively - nested components.
With a shared service and an RxJS, non-nested components can also subscribe to the property and act accordingly when changed. Below is the simple example that emits a new value when this.myService.update()
method is called from anywhere within an application:
// myservice.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {
wat$: Subject<any>;
constructor() {
this.wat$ = new Subject();
}
update() {
this.wat$.next(new Date().getTime());
}
}
Then the component relied on the service can subscribe to and act.
// mycomponent.ts
export class MyComponent {
constructor(private myService: MyService) {
this.myService.wat$.subscribe((value) => {
// do something with the new value
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With