2

I have a function myFunc() which i subscribe to.

If it is called with X then i want it to be a normal HTTP response from the Server.

If it is called without X, i want it to return a 'fake' http response with an empty array as a result.

How can i do this? I have tried returning an empty observable, but the subscribe never triggers.

myFunc(x) {
  if (x) {
    return this.http.get('myURL');
  } else {
    return Observable.from<Response>([])
  }
}
martin
  • 93,354
  • 25
  • 191
  • 226
Nabil A
  • 71
  • 3

3 Answers3

1

Just replace Observable.from<Response>([]) with Observable.of<Response>([]).

return Observable.of<Response>([])

This is because Observable.from iterates the input array and emits all its items. Since the array is empty it won't emit anything. Observable.of just takes what you pass as a parameter and sends it as next followed by the complete notification.

martin
  • 93,354
  • 25
  • 191
  • 226
0

You can return something like this and it will trigger your subscription:

return Observable.of<any>({ isSuccess: false });

Here you can pass any object. I just created simple object { isSuccess: false }

Rukshan Dangalla
  • 2,500
  • 2
  • 24
  • 29
0

Observable.empty won't trigger the onNext function of the subscription, but will trigger the onComplete. You could put some of this logic there. Alternatively, you could use

return Observable.just(null);

to return an Observable with null data

Josh
  • 444
  • 1
  • 7
  • 19