Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store global data in Angular?

Tags:

angular

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?

like image 319
Expressingx Avatar asked Apr 27 '18 17:04

Expressingx


2 Answers

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.

like image 112
Lucas Avatar answered Oct 20 '22 14:10

Lucas


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.

like image 42
tilo Avatar answered Oct 20 '22 13:10

tilo