I decided to learn Angular 4 and ASP Net Core 2 at once by building blog application. I came to a point where I want to store global data for every component.
For example, I want when the user logs in to pass the logged state to my navbar component and by that I can change the buttons, show the current user name etc.
How from my LoginComponent I can pass data to my NavbarComponent and so on?
Stackblitz with example of how to apply observable and @Input data changes accross components with a service.
You will need a service and Rxjs with subscriptions to do it the angular way:
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class UserNameService {
execChange: Subject<any> = new Subject<any>();
constructor() {}
/**
* Use to change user name
* @data type: string
*/
userNameChange(data: string) {
this.execChange.next(data);
}
}
And then in every component where you want to have the user name changed add a subscription:
constructor(private userNameService : UserNameService) {
this._subscription_user_name = this.userNameService.execChange.subscribe((value) => {
this.userName= value; // this.username will hold your value and modify it every time it changes
});
}
How to change the value so that every subscription can moddify the values? Call your execChange
function in your service:
this.userNameService.userNameChange('Thor');
EDIT: @Vikas comment is correct and quite self explanatory... youn need to add the service to ngModule providers array or you will get a headache dealing with unknown provider errors.
@NgModule({
imports: [
...
],
declarations: [...],
providers: [UserNameService]
})
If you need to persist your data across tabs or when refreshing the page, use localstorage
as well.
It might be overkill for starting to learn Angular, but as @ShellNinja pointed out, you might consider a library offering state management, e.g. ngrx.
From the @ngrx/store docs:
RxJS powered state management for Angular applications, inspired by Redux
@ngrx/store is a controlled state container designed to help write performant, consistent applications on top of Angular. Core tenets:
State is a single, immutable data structure. Actions describe state changes. Pure functions called reducers take the previous state and the next action to compute the new state. State accessed with the Store, an observable of state and an observer of actions. These core principles enable building components that can use the OnPush change detection strategy giving you intelligent, performant change detection throughout your application.
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