Isaac Levin Isaac Levin - 25 days ago 16
TypeScript Question

Sharing Objects between Components Angular 2

I have an app that is authenticating a user and returning some information about them (name, email address, etc) that I want to populate through the app, but I do not want to have to constantly get this data from storage or subscribe to some event to get this information. Is there a way to declare a global "User" for instance and be able to access it from any component in the application, whether they are related or not?

Answer

Look at creating a shared module. You place behavior in it that you need to share with other components. Here's a sample shared module from my app (I left out all the import statements):

@NgModule({
  imports: [CommonModule, RouterModule, ReactiveFormsModule, 
            MenubarModule, GalleriaModule, InputTextModule, PanelModule, ButtonModule, DropdownModule, DialogModule, AccordionModule, 
            CalendarModule, SelectButtonModule, CheckboxModule, ProgressBarModule, DataTableModule, DataListModule, ConfirmDialogModule],
  declarations: [ ErrorMessagesComponent, FoodDashboardComponent, KgNumberSpinnerComponent, KgDateSpinnerComponent ],
  exports: [ CommonModule, ReactiveFormsModule, HttpModule, RouterModule, 
            MenubarModule, GalleriaModule, InputTextModule, PanelModule, ButtonModule, DropdownModule, DialogModule, AccordionModule, CalendarModule,
            SelectButtonModule, CheckboxModule, DataTableModule, DataListModule, ProgressBarModule, ErrorMessagesComponent, FoodDashboardComponent,
            KgNumberSpinnerComponent, KgDateSpinnerComponent, ConfirmDialogModule, TooltipModule ]

})

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [SettingsService, AppMenuService, AuthorizationService, LoginService, LogoutService, RegisterService, ThemeService, ValidationService,
        NutritionixService, AuthGuardService, CanDeactivateGuardService, CalculationService, ChallengeService, FoodService, ConfirmationService ]
    };
  }
}

With this shared module, all that behavior is available to any component simply by importing the shared module in the components module definition.

Sample component module:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { HomeComponent } from '../home/home.component';
import { LoginComponent } from '../home/login/login.component';
import { RegisterComponent } from '../home/register/register.component';
import { VerifyComponent } from '../home/verify/verify.component';
import { VerifyEmailComponent } from '../home/verifyEmail/verifyEmail.component';
import { ValidationService } from '../services/validation.service';
import { ForgotComponent } from '../home/login/forgot/forgot.component';
import { ForgotVerifyComponent } from './login/forgotVerify/forgotVerify.component';
import { ChangeComponent } from '../home/login/change/change.component';
import { ChallengeComponent } from '../home/login/challenge/challenge.component';
import { LogoutComponent } from './logout/logout.component';
import { SharedModule }   from '../shared/shared.module';
import {routeConfig} from './home.routing'


@NgModule({
    imports: [ SharedModule, RouterModule.forChild(routeConfig)],
    declarations: [ HomeComponent, LoginComponent, RegisterComponent, VerifyComponent, 
                   VerifyEmailComponent, ForgotComponent, ForgotVerifyComponent, 
                   ChangeComponent, ChallengeComponent, LogoutComponent ], 
    exports: [ HomeComponent ]

}) 

export class HomeModule {

} 

Sample Component you requested:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../../services/login.service';
import { LogoutService } from '../../services/logout.service';
import { ConfirmationService } from 'primeng/primeng';

@Component({

  selector: 'app-logout',
  templateUrl: 'logout.component.html',
  styleUrls: ['logout.component.css']
})
export class LogoutComponent implements OnInit {

  constructor(
    private r: Router,
    private cfs: ConfirmationService,
    private ls: LoginService,
    private los: LogoutService
  ) {

  }

  ngOnInit() {

  }

  confirmLogout() {
    this.cfs.confirm({
      message: 'Do you want to logout of Ketogeniq?',
      header: 'Logout Confirmation',
      icon: 'fa fa-sign-out',
      accept: () => {
        this.logout();
      },
      reject: () => {
        this.cancel()
      }
    });
  }


  cancel() {
    this.r.navigate(['/home'])
  }

  logout() {
    console.log('setting logout');
    this.los.setLogout(true);
  }
}
Comments