2016-12-28 42 views
0

有沒有辦法使用loadChildren(延遲加載組件)提供@Injectable作爲單例加載組件?Angular2:惰性加載組件和注入單元作爲單例

如果沒有,有沒有辦法得到它?我想問它this post。據此,不可能在子模塊上注入@Injectable作爲單例。

我試圖注入一個@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 
    ] 
}) 
export class AppModule { 
    constructor(public appRef: ApplicationRef, public appState: AppState) {} 
} 

所以,我也創建了一個"submodule"

@NgModule({ 
    //... 
    providers: [ 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是未定義的,如果我之前在另一個組件中設置?

+0

不要在延遲加載_modules_的級別提供它。您必須在'app.module'級別提供它(或者如果您在'core.module'中使用了一個)。 –

+0

[這篇文章](http://stackoverflow.com/a/40981772/217408)呢? – Jordi

回答

2

這篇文章解釋了你需要知道的一切。在延遲加載的模塊中聲明的任何服務只會是該模塊的單例。加載到根模塊中的任何服務都將是整個應用程序中的單例,包括內部惰性加載的模塊

+0

我已編輯帖子。據此。如果我在'AppModule(構造函數(私有appState:AppState))'上注入'AppState','LoginComponent'和'ProfileComponent'應該是同一個對象(單例),不是嗎?然而,'this.appState.user'總是'undefined',無論'LoginComponent'是否分配了它... – Jordi

+0

@Jordi爲什麼你要在'ProfileModule'和'LoginModule'的提供者數組中聲明'AppState'?你是否試圖僅在'AppModule'中聲明它? – yurzui

+0

我以爲它必須在每個請求的模塊中聲明爲提供者...... – Jordi

1

全部@Injectable()服務是單身人士。加載組件是路由器的工作,而不是服務。

+0

[這篇文章](http://stackoverflow.com/a/40981772/217408)呢? – Jordi