Angular2.x APP_INITIALIZER

APP_INITIALIZER是在Angular2.x程序啓動以前執行的一個函數,能夠在這個裏面進行自動登陸,判斷登陸token,阻止啓動等一系列操做,能夠在AppModule類的providers中以factory的形式來配置,factory是一個返回值爲promise的函數。git

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initApp,
            deps: [HttpClient],
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

下面咱們看initApp的定義,注意必定要是返回值爲Promise的函數github

簡單的一個Projmise例子
export function initApp() {
  return () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('In initApp');
        resolve(); //reject() 就會終止程序的啓動
      }, 3000);
    });
  };
}

獲取一種信息
export function initApp(http: HttpClient) {
  return () => {
    return http.get('https://api.github.com/users/sagar-ganatra')
      .toPromise()
      .then((resp) => {
        console.log('Response 1 - ', resp);
      });
  };
}

登陸後獲取一種信息
export function initApp(http: HttpClient) {
  return () => {
    return http.get('login').toPromise()
      .then((resp) => {
                this.user = resp.user;
                return this.http.get('fileInfo').toPromise();
      });
  };
}
相關文章
相關標籤/搜索