我们应该订阅一个 void 函数吗?如何订阅?

Should we subscribe to a void function and how?

使用 promise 很简单,因为我可以告诉函数 return 类型的 void 函数是 Promise(我希望我是对的)。

我想对 Observables 做同样的事情,所以它会是这样的:

import {Observable, Subject} from "rxjs/Rx"

...
private personArray:Person[] = PERSONS; ///some persons in other file.
...

///This fucntion remove one person from my service.

public remove(id:number):Observable<void> {
    this.personArray = this.personArray.filter(person1=>person1.id !== id);
    return Observable.from(); ???
  }
  1. 订阅者不会知道第一行是否抛出错误。我确信有更好的方法可以做到这一点,我会很高兴看到任何其他解决方案。
  2. 我怎样才能让这段代码起作用?

谢谢。

如果您只需要 OnCompleted 消息,请使用 Observable.empty(). If an error happens, you can use Observable.throw(...):

public remove(id:number):Observable<void> {
  try {
    this.personArray = this.personArray.filter(person1=>person1.id !== id);
    return Observable.empty();
  } catch (e) {
    return Observable.throw(e);
  }
}

或者,您可以使用 .defer()。如果您的函数抛出异常,则会(自动)抛出 OnError:

public remove(id:number):Observable<void> {
  return Observable.defer(() => {
    this.personArray = this.personArray.filter(person1=>person1.id !== id);
    return Observable.empty();
  });
}

因为你不能真正使用 void 并且类型并不重要,因为没有人会尝试解释任何值,只需使用 any:

public remove(id:number):Observable<any> {
    this.personArray = this.personArray.filter(person1=>person1.id !== id);
    return Observable.empty<any>();
}