Angular2:注射作为单(Angular2: Injectable as singleton)

2019-09-29 19:32发布

我试图注入的@Injectable AppState作为单:

@Injectable()
export class AppState {
  public user: string;

  constructor() {

  }
...

我已经把它放在AppModuleprovider

// Application wide providers
const APP_PROVIDERS = [
  AppState
];

@NgModule({
  bootstrap: [ App ],
  declarations: [
    App,
    ErrorComponent
  ],
  imports: [ // import Angular's modules
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(ROUTES, { useHash: true })
  ],
  providers: [
    APP_PROVIDERS
  ]
})

所以,我刚刚创建了"submodule"

@NgModule({
  //...
  providers: [ UsersService, AppState ]
})
export default class LoginModule {

LoginComponent我做的:

export class Login implements OnInit {

    constructor(private appState: AppState) {}

    public doLogin():void {
        this.appState.user = this.form.value.mail;
    }
}

然而,在另一个组件命名Profile ,似乎this.appState.user是不确定的。

@NgModule({
  //...
  providers: [ AppState ]
})
export default class ProfileModule { /... }

@Component({
  //...
})
export class Profile implements OnInit {

  constructor(private appState: AppState) {

  }

  ngOnInit():void {
    this.user = this.appState.user;  <<<<<<<<<<<<< it's undefined
  }
}

为什么this.appState.user在另一个组件undifined如果I'set之前?

文章来源: Angular2: Injectable as singleton
标签: angular