在组件之间共享对象Angular 2

时间:2016-11-07 15:45:28

标签: angular typescript

我有一个应用程序正在验证用户并返回我想要通过应用程序填充的一些信息(名称,电子邮件地址等),但我不想不断从存储中获取此数据或订阅某些事件以获取此信息。有没有办法宣布一个全球性的用户"例如,能否从应用程序中的任何组件访问它,无论它们是否相关?

1 个答案:

答案 0 :(得分:1)

查看创建共享模块。您在其中放置了需要与其他组件共享的行为。这是我的应用程序中的示例共享模块(我遗漏了所有的import语句):

@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 ]
    };
  }
}

使用此共享模块,只需在组件模块定义中导入共享模块,所有组件都可以使用所有这些行为。

示例组件模块:

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 {

} 

您请求的示例组件:

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