Angular 2 Dart: How to share variables between parent with router and child components?
On the parent component provide a shared service
@Injectable()class SharedService { bool _isUserLoggedIn = false; bool get isUserLoggedIn => _isUserLoggedIn; set isUserLoggedIn(bool value) { _isUserLoggedIn = value ?? false; _isUserLoggedInController.add(_isUserLoggedIn); } StreamController<bool> _isUserLoggedInController; Stream<bool> get onIsUserLoggedIn => _isUserLoggedInController.stream; SharedService() { _isUserLoggedInController = new StreamController<bool>.broadcast( onListen: () => _isUserLoggedInController.add(_isUserLoggedIn) ); }}
In components where you want to update use or update the status inject the service
@Component( ..., template: ''' <div>isLoggedIn: {{sharedService.onIsUserLoggedIn | async}}</div> <button (click)="toggleIsUserLoggedIn()">{{(sharedService.onIsUserLoggedIn | async) ? 'log out' : 'log in'}}</div> ''',)class SomeComponent { final SharedService sharedService; SomeComponent(this.sharedService); toggleIsUserLoggedIn() { sharedService.isUserLoggedIn = !sharedService.isUserLoggedIn; }}
Provide the service in AppComponent
@Component( selector: 'my-app', providers: const [SharedService],)class AppComponent {}
This is how I achieved this. Using a shared service.
In component where the model is being updated/used:
class myClassSend { constructor(private sharedService: SharedService){ this.sharedService.userStatusUpdate(this.isUserLoggedIn); // We send isUserLoggedIn value to the shared service }}
Our shared service could be something like:
export class SharedService { userStatusUpdate$: Observable<any>; private userStatusUpdateSubject = new Subject<any>(); constructor() { this.userStatusUpdate$ = this.userStatusUpdateSubject.asObservable(); } userStatusUpdate(userStatus) { this.userStatusUpdateSubject.next(userStatus); }}
In component where we want to know the value of the model:
class myClassReceive { bool isUserLoggedIn; constructor(private sharedService: SharedService){ this.sharedService.userStatusUpdate$.subscribe((userStatus) => { this.isUserLoggedIn = userStatus; // And here we receive the isUserLoggedIn value! } );}
Now, think that from myClassSend
you can send the information whenever you want: onInit, onChange, etc... And myClassReceive
will be "listening" all the time and will receive the value that you are sending as a parameter to the shared service.
Think of the shared service as a cell phone that communicates 2 people (components), sending messages (parameters/data).
Here is Angular's documentation: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service