APP_INITIALIZER函數(shù)的使用方法

這篇文章給大家分享的是APP_INITIALIZER函數(shù)的使用方法。小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí)。如下資料是關(guān)于APP_INITIALIZER的內(nèi)容。

創(chuàng)新互聯(lián)建站主要從事成都做網(wǎng)站、成都網(wǎng)站制作、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)漢臺(tái),十多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792

APP_INITIALIZER是在Angular2.x程序啟動(dòng)之前執(zhí)行的一個(gè)函數(shù),可以在這個(gè)里面進(jìn)行自動(dòng)登錄,判斷登錄token,阻止啟動(dòng)等一系列操作,可以在AppModule類的providers中以factory的形式來配置,factory是一個(gè)返回值為promise的函數(shù)。

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的函數(shù)

簡(jiǎn)單的一個(gè)Projmise例子
export function initApp() {
  return () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('In initApp');
        resolve(); //reject() 就會(huì)終止程序的啟動(dòng)
      }, 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();
      });
  };
}

看完上述內(nèi)容,你們掌握APP_INITIALIZER函數(shù)的使用方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

分享名稱:APP_INITIALIZER函數(shù)的使用方法
URL網(wǎng)址:http://muchs.cn/article24/jpidje.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、軟件開發(fā)、企業(yè)網(wǎng)站制作、外貿(mào)建站、網(wǎng)站改版品牌網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化