1

I have two functions that return an Observable :

//get a new entity from server
public new(): Observable<any> {
  return this.http.get<any>(api + 'New');
}

//create the entity
public create(data: any) {
  return this.http.post(api + 'Update', data);
}

Now, I need to write a function that calls these two functions and returns an Observable :

addNewItem(value: any): Observable<any> {
  this.service.new().subscribe(x => {
      // do something with "X" 
      return this.service.create(x);
  });
}

But, this does not work because return is inside subscribe.

Littm
  • 4,923
  • 4
  • 30
  • 38
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84

2 Answers2

1

You can use switchMap from rxjs operators.

addNewItem(value: any): Observable<any> {
  return this.service.new().pipe(switchMap(x => this.service.create(x))
}

see the following link for more details: Angular4 - Nested Http Calls

alt255
  • 3,396
  • 2
  • 14
  • 20
0

In this case you could use RxJS switchMap operator. Try the following

addNewItem(value: any): Observable<any> {
  return this.service.new().pipe(switchMap(x => {   // <-- note the `return` here
    // do something with "X" 
    return this.service.create(x);
  }));
}

Why two return statements?

The inner statement return this.service.create(x); denotes the observable to be switched to when handling the observable returned by this.service.new().

The outer statement return this.service.new() denotes the observable to be returned by the function addNewItem(). In this case we switched it to the observable from this.service.create(x).

One more thing to note about arrow functions:

this.service.new().pipe(switchMap(x => this.service.create(x)));

is similar to

this.service.new().pipe(switchMap(
  x => {
    return this.service.create(x);
  }
));

Essentially with the curly braces, the return statement must be explicitly stated.

ruth
  • 29,535
  • 4
  • 30
  • 57