angular2 从 Observable 获取字符串值到本地 var

angular2 getting string value out of Observable into local var

我有一个函数 return 一个包含字符串的 Observable,像这样:

retrieveDialingCode(countrycode: string): Observable<any> {
    return this.countries.map(res => res
          .find(country => country.alpha2 === countrycode)
          .countryCallingCodes[0]
      .replace(/\D/g, ''));
}

当我这样使用它时效果很好:

this.retrieveDialingCode(countrycode).subscribe(res => this.phone.patchValue( { isodialingcode: res } ) );

然而,当我像这样使用它时,我只在 dialingCode 中得到一个对象:

const dialingCode = this.retrieveDialingCode(phone.isocountrycode).subscribe(res => console.log(res));

我做错了什么?

这是因为在最后一种情况下您的代码没有 return 响应,请尝试使用此:

let dialingCode;
this.retrieveDialingCode(phone.isocountrycode).subscribe(res => {
  dialingCode = res;
});

这里我只是将 subscribe 的响应存储到 dialingCode 变量。

Observable 的 'problem' 是它们不能轻易地转换为值然后在同步代码中使用,因为您总是必须等待 Observable 发出。

真的,您应该拥有所有依赖于 retrieveDialingCode inside 订阅结果的代码,按照你的第一次使用。

您可能会找到规律

let myVar;
myObservable.subscribe(value => myVar = value);
somethingThatUsesMyVar(myVar);

有时会起作用,但解析 myObservable 时的任何延迟都意味着 myVar 不会有预期的值。

请注意,如果 this.countries 不是一个可观察对象而是一个数组,您可以将 retrieveDialingCode return 设为展开值而不是可观察对象,那么没问题。