Murhaf Sousli Murhaf Sousli - 3 months ago 177
TypeScript Question

How to return an empty observable in rxjs

The function

more()
is supposed to return an
Observable
from a get request

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();
}
);
}
}


In this case I can only do a request if
hasMore()
is true, if it's not I'm getting an error on
subscribe()
function
subscribe is not defined
, how can I return an empty observable?

this.collection.more().subscribe(
(res) =>{
console.log(res);
},
(err) =>{
console.log(err);
}
)

Answer

Yes, there is am Empty operator

Rx.Observable.empty();

For typescript, you can use from:

Rx.Observable<Response>.from([])