簡體   English   中英

角度:在APP_INITIALIZER中發送HTTP請求之前,加載配置文件

[英]Angular: Load config file before sending http request within the APP_INITIALIZER

在我的SPA中,我正在使用APP_INITIALIZER令牌,該令牌應按照給定的順序執行以下操作。 1)加載與環境相關的配置文件(DEV,QA,PROD)。 2)使用配置文件中的API URL發出對身份驗證令牌的HTTP請求3)使用配置文件中的API URL並將令牌附加到HTTP請求(這在令牌攔截器中發生)以加載其他配置數據)

之前我用硬編碼的URL實現了2和3,然后一切正常。 當我將API Urls移動到配置並嘗試從配置文件加載它們時,令牌端點在配置文件請求得到解決之前就已執行,因此url變得不確定。

請參見下面的代碼:

app.module.ts

export function initializeData(appConfig: AppConfig, authService: AuthService, appService: AppService, globalService: GlobalService) {
  return () => {
    try {
      return Promise.all([appConfig.load(), authService.authenticateClient(), appService.getClientConfig()]).then(() => {
        console.log('success')
        return Promise.resolve();
      }, (err) => {
        alert(err.error.error_description);
        return Promise.reject(err);
      });
    } catch (e) {
      alert(e.message);
      console.log(e);
    }

  }
}

@NgModule({
.............
.............
providers: [
    AppConfig,
    AuthService,
    {
      provide: APP_INITIALIZER,
      useFactory: initializeData,
      deps: [AppConfig, AuthService, TranslateService, AppService, GlobalService],
      multi: true
    },
    AppService
]
});

app.config.ts:

@Injectable()
export class AppConfig {
  static settings: IAppConfig;
  constructor(private http: HttpClient) { }
  load() {
    const jsonFile = `assets/config/config.${environment.name}.json`;

    return new Promise((resolve, reject) => {
      this.http.get(jsonFile).pipe(map((res: IAppConfig) => {
        AppConfig.settings = <IAppConfig>res;
        return AppConfig.settings;
      })).subscribe(() => {
        resolve();
        })
    }).catch ((response: any) => {
        console.log(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
      });
  }
}

auth.service.ts(令牌端點):

authenticateClient(){
    let body = new HttpParams()
      .set('client_id', AppConfig.settings.apiServer.client_id)
      .set('grant_type', AppConfig.settings.apiServer.grant_type)
      .set('scope', AppConfig.settings.apiServer.scope);

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      })
    };

    let authGatewayUrl: string = AppConfig.settings.apiServer.tokenUrl + window.location.search;

    return  this.http.post<any>(authGatewayUrl, body, httpOptions).toPromise().then(
        data => {
          this.token.next(data); 
          return this.token;
        },
        error => {
          return Promise.reject(error);
        }
      );  
  }

現在,當我在app.config.ts和auth.service.ts中添加斷點時,在后者文件中,AppConfig.Settings.apiServer.tokenUrl會在應用程序配置文件解析之前被命中。 因此,它變得不確定。

我該如何解決? 我知道我應該使用switchmap,但是我不確定如何處理它。

也許您可以控制.then回調中的順序:

appConfig.load()
  .then(()=>
     Promise.all[
       authService.authenticateClient(),
       appService.getClientConfig()
     ]
     .then....)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM