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
});
}
}