RX JS синхронизация звонков - PullRequest
0 голосов
/ 05 марта 2020

В моей службе есть код, который выбирает токен из родительского элемента iframe и использует этот токен для вызова rest.

Ниже приведен фрагмент кода для метода, выполняющего вызов GET REST.

public get_agencyschema() {
return this.tokenService.authenticatedToken.pipe(
  map(token => {
    const opt = {
      headers: new HttpHeaders({
        Authorization: token
      })
    };
    console.log('get_agency %%%%%%%%%%%%%%%%%%%%%%%% ' + token);

    return this.http.get(this.baseUrl', opt);
  }));
}

Когда я вызываю этот метод из моего компонента, я получаю неопределенное значение. Вот код для моего компонента.

private doSomething() {
this.rest.get_agencyschema().subscribe(data => {
  /* tslint:disable:no-string-literal */
  this.ccConfig = data['_embedded']['item'];
  /* tslint:enable:no-string-literal */
  for (let index = 0; index < Object.keys(this.ccConfig).length; index++) {
    if (Object.keys(this.ccConfig[index].configuration).length > 0) {
      this.Schema = this.ccConfig[index];
      // console.log(this.Schema);
      break;
    }
  }
  // console.log(this.Schema.configuration);
  this.LocationVerifyForm.setValue({
    MatchDistance: this.Schema.configuration.MatchDistance,
    IsReturnClosestMatch: this.Schema.configuration.IsReturnClosestMatch,
    WildcardCharacters: this.Schema.configuration.WildcardCharacters,
    IntersectionDelimiterCharacters: this.Schema.configuration.IntersectionDelimiterCharacters,
    MaxReturnResults: this.Schema.configuration.MaxReturnResults,
    IsDisplayHighAndLowCrossStreets: this.Schema.configuration.IsDisplayHighAndLowCrossStreets,
    IsDisplayHighAndLowCrossBlocks: this.Schema.configuration.IsDisplayHighAndLowCrossBlocks,
    IsDisplayBlockNumbersForIntersections: this.Schema.configuration.IsDisplayBlockNumbersForIntersections,
    DisableAutoSelectVerifiedLocation: this.Schema.configuration.DisableAutoSelectVerifiedLocation,
    IsDisplayTableOfContent: this.Schema.configuration.IsDisplayTableOfContent,
    DistanceInMeter: this.Schema.configuration.DistanceInMeter,
    Direction: this.Schema.configuration.Direction,
    IsFilterBeatsByCityEnabled: this.Schema.configuration.IsFilterBeatsByCityEnabled,
    CascadeLevel: this.Schema.configuration.CascadeLevel,
    BlockKeyword: this.Schema.configuration.BlockKeyword,
    BlockDisplayFormat: this.Schema.configuration.BlockDisplayFormat,
    BlockGeoCodeLocation: this.Schema.configuration.BlockGeoCodeLocation,
    IsRetainInvalidPremiseNumber: this.Schema.configuration.IsRetainInvalidPremiseNumber,
    GeoDatabase: this.Schema.configuration.GeoDatabase
  });
});
this.LocationVerifyForm = new FormGroup({
  MatchDistance: new FormControl(),
  IsReturnClosestMatch: new FormControl(),
  WildcardCharacters: new FormControl(),
  IntersectionDelimiterCharacters: new FormControl(),
  MaxReturnResults: new FormControl(),
  IsDisplayHighAndLowCrossStreets: new FormControl(),
  IsDisplayHighAndLowCrossBlocks: new FormControl(),
  IsDisplayBlockNumbersForIntersections: new FormControl(),
  DisableAutoSelectVerifiedLocation: new FormControl(),
  IsDisplayTableOfContent: new FormControl(),
  DistanceInMeter: new FormControl(),
  Direction: new FormControl(),
  IsFilterBeatsByCityEnabled: new FormControl(),
  CascadeLevel: new FormControl(),
  BlockKeyword: new FormControl(),
  BlockDisplayFormat: new FormControl(),
  BlockGeoCodeLocation: new FormControl(),
  IsRetainInvalidPremiseNumber: new FormControl(),
  GeoDatabase: new FormControl()
});
}

Я новичок в RX JS и Observables. Может кто-нибудь, пожалуйста, помогите мне выяснить проблему с тем, как получить ответ метода GET в методе компонента.

Заранее спасибо.

1 Ответ

1 голос
/ 05 марта 2020

В rx js вы бы не "сопоставляли" с новой наблюдаемой, но вы бы использовали "switchMap" (если всегда может быть активен только один вызов) или "mergeMap" (если несколько выполнений могут выполняться параллельно).

return this.tokenService.authenticatedToken.pipe(
  switchMap(token => {
    const opt = {
      headers: new HttpHeaders({
        Authorization: token
      })
    };
    console.log('get_agency %%%%%%%%%%%%%%%%%%%%%%%% ' + token);

    return this.http.get(this.baseUrl', opt);
  }));
}

Теперь вы возвращаете наблюдаемое, которое доставит результат вызова http get.

...