需要 RxJS 说明:如何 return 普通对象而不是 Observable

RxJS clarification needed: how to return a plain object instead of an Observable

我正在编写一个 angular 2 验证器函数。我想 return 一个 普通对象 而不是 observable.

这是我当前的实现:

import {AbstractControl} from "@angular/common";
import {UserAccountService} from "../../useraccount/useraccount.service";

export function validateEmailAvailable(userAccountService: UserAccountService) {
  return (control: AbstractControl)=> { //This returned lambda should itself return a plain object
    return userAccountService.checkAvailability(control.value)
      .map(res=> {
        if (res.json() === true) {
          return null;
        }
        else {
          return {unavailable: true};
        }
      });
  };
}

有人可以解释一下如何正确使用 RxJs 运算符,以便 return 上面的 null{unavailable: true} 但不是可观察的吗?

我敢打赌这是不可能的。这与要求异步函数同步 return 其值相同。或者 return 根据未来的价值计算出现在的价值。它本质上是矛盾的。如果您考虑一下,Promise 'operators' 也将永远是 return 一个承诺。

您可以使用 toPromise() 来 return 承诺而不是 Observable。 例如:

export function validateEmailAvailable(userAccountService: UserAccountService) {
  return (control: AbstractControl)=> { //This returned lambda should itself return a plain object
    return userAccountService.checkAvailability(control.value)
      .toPromise()
      .then(res=> {
        if (res.json() === true) {
          return null;
        }
        else {
          return {unavailable: true};
        }
      });
  };
}

而不是 returning lambda 为什么不直接 return 包含值的可观察值?