在我的延迟加载的模块中未定义Angular 2服务属性值

时间:2016-11-17 14:34:07

标签: angular angular-cli

我在服务中有几个属性,我想在其他延迟加载的模块中共享

我的服务定义为:

@Injectable()
export class AppSettingsService {

  private _deviceId: string;
  private _accountId: string;

  constructor() { }

  initialise(): Promise<any> {


    if(this.getDeviceIDFromLocalStorage() && this.getAccountIDFromLocalStorage()) {
      return Promise.resolve(ErrorCode.EXISTING_USER);
    } 

  }

  setApplicationId(applicationId): void {
    this._deviceId = applicationId;
  }

  getApplicationId(): string {
    return this._deviceId;
  }

  setAccountId(accountId): void {
    this._accountId = accountId;
  }

  getAccountId(): string {
    if(typeof this._accountId !== 'undefined') {
      return this._accountId;
    } else {
      return '0';
    }
  }


  public getDeviceIDFromLocalStorage(): Boolean {
    let deviceID = localStorage.getItem(appkeys.DEVICE_ID);

    if((typeof deviceID !== 'undefined') && (deviceID !== null)){
      this.setApplicationId(deviceID);
      return true;
    } else {
      return false;
    }
  }

  public getAccountIDFromLocalStorage(): Boolean {
    let accountId = localStorage.getItem(appkeys.ACCOUNT_ID);

    if((typeof accountId !== 'undefined') && (accountId !== null)){
      this.setAccountId(accountId);
      return true;
    } else {
      return false;
    }
  }



}

我在共享模块中宣布该服务

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { LogoComponent } from './logo.component';
import { AppSettingsService } from './app-settings.service';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    LogoComponent
  ],
  exports: [
    CommonModule,
    FormsModule,
    RouterModule,
    LogoComponent
  ]
})

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [ AppSettingsService ]
    }
  }
}

核心应用中的所有数据都可以正常加载。当我导航到另一个延迟加载的模块,并调用getApplicationId()或getAccountId()时,属性_deviceId和_accountId是未定义的。

在我的延迟加载模块中,我导入了共享模块

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { SharedModule } from '../shared/shared.module';
<excluded for clarity>

@NgModule({
  imports: [
    CommonModule,
    HttpModule,
    SharedModule.forRoot(),
  ],
  declarations: [
    <excluded for clarity>

  ],
  providers: [
    <excluded for clarity>

  ]
})
export class AdvertisementModule { }

在我的组件中,我导入服务

import { AppSettingsService } from '../shared/app-settings.service’;

并在构造函数中引用它

constructor(private _router: Router, private _appService: AppSettingsService) { }

我错过了什么或者不能以这种方式在服务中保留值?我正在使用angular-cli webpack 2.1.0-beta.25

0 个答案:

没有答案