使HTTP调用在超时后返回Observable

时间:2019-07-19 14:25:37

标签: angular service ngx-translate

我正在我们的应用程序中实现@ ngx-translate。要获取翻译,我们使用后端API。我已经使用TranslationLoader(实现TranslateLoader)编写了一个类来获取翻译。要进行API调用,我需要Auth0返回的访问令牌。通过服务设置此访问令牌需要一些时间,并且在此之前TranslationLoader已经向BE发出了请求。由于缺少访问令牌,此操作失败。有人可以建议一些替代方法吗?

我已经尝试过使用RxJS中的delay和retryWhen,但是它作用于Observable而不作用于http请求,所以没有用。

translation-loader

  constructor(private http: HttpClient, private authService: AuthService, private configService: ConfigService) {}

  /**
   * The getTranslation method returns the Observables with the requested language translations
   * @param language is the string specifying which language's translation is requested.
   */
  getTranslation(language: string): Observable<any> {
    const transactionsConfig = this.configService.transactionServiceConfig;
    let authHeaderValue = {};
    try {
      if (authHeader()) {
        authHeaderValue = authHeader();
      }
    } catch {
      this.authService.logout();
    }
    return this.http.get(`${transactionsConfig.apiUrl}/dictionary/translations/ln/${language}`, {
      headers: authHeaderValue,
    })
      .pipe(
        map((result) => {
            return this.processTranslations(result);
          }
        ),
      );
  }

  processTranslations(translationCollection: object): object {
    const newObject = {};

    for (const key in translationCollection) {
      if (translationCollection.hasOwnProperty(key)) {
        if (typeof translationCollection[key] === 'object') {
          newObject[key] = this.processTranslations(translationCollection[key]);
        } else if ((typeof translationCollection[key] === 'string') && (translationCollection[key] === '')) {
          // do not copy empty strings
        } else {
          newObject[key] = translationCollection[key];
        }
      }
    }
    return newObject;
  }
}

0 个答案:

没有答案