more()
函数应该从一个 get 请求中返回一个 Observable
export class Collection {
public more = (): Observable<Response> => {
if (this.hasMore()) {
return this.fetch();
} else {
// return empty observable
}
};
private fetch = (): Observable<Response> => {
return this.http.get("some-url").map((res) => {
return res.json();
});
};
}
在这种情况下,我只能在hasMore()
返回true时发出请求,否则在subscribe()
函数上会出现错误subscribe is not defined
。那么我该如何返回一个空的Observable呢?this.collection.more().subscribe(
(res) => {
console.log(res);
}, (err) => {
console.log(err);
}
);
of()
来完成。 - Matthijs Wesselsof('foo')
会立即发出并完成可观察对象。https://rxviz.com/v/0oqMVW1o - SimplGytake(1)
已经移除了,以便得到更好的答案。@MatthijsWessels,是和不是,我现在刚测试过,如果你使用of()
,它会返回一个完整的可观察对象,而不会发出next
。 - Stephen LautierEMPTY
与.subscribe()
的关系。例如,EMPTY.subscribe(() => {console.log('test');})
可能不会像你想象的那样工作。更多信息请参见 https://blog.novanet.no/rxjs-getting-fooled-by-empty-observables/。 - Liam