angular2将字符串值从可观测值转换为局部变量

angular2将字符串值从可观测值转换为局部变量,angular,subscribe,Angular,Subscribe,我有一个函数,它返回一个包含字符串的可观察对象,如下所示: retrieveDialingCode(countrycode: string): Observable<any> { return this.countries.map(res => res .find(country => country.alpha2 === countrycode) .countryCallingCodes[0] .replace

我有一个函数,它返回一个包含字符串的可观察对象,如下所示:

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 } ) );
const dialingCode = this.retrieveDialingCode(phone.isocountrycode).subscribe(res => console.log(res));

我做错了什么?

这是因为在最后一种情况下,您的代码没有返回响应,请尝试使用以下方法:

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

这里我只存储
subscribe
diallingcode
变量的响应。

可观察对象的“问题”是它们不能很容易地转换为值,然后在同步代码中使用,因为您总是要等待可观察对象发出

实际上,根据您的首次使用情况,您应该将所有依赖于
retrieveDialingCode
结果的代码都放在订阅中

你可以找到模式

let myVar;
myObservable.subscribe(value => myVar = value);
somethingThatUsesMyVar(myVar);
在一段时间内会起作用,但在解析
myObservable
时的任何延迟都意味着myVar将不具有预期值


注意,如果
this.countries
不是可观察的,而是一个数组,您可以让
retrieveDialingCode
返回未包装的值而不是可观察的值,那么没有问题。

是的,我以前做过,但异步是一个问题。取决于retrieveDialingCode结果的代码有点广泛,但如果这是唯一的选项,那么我可以将其放在订阅中,有点难看,这很烦人。您可以通过将下游代码放入一个方法来稍微美化它,然后
subscribe()
只需要在其中插入一行代码,即调用该方法并传递值。(很抱歉,如果这已经很明显了)。