Beetlejuice
Beetlejuice

Reputation: 4425

Return an observable after two operations

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.

Upvotes: 1

Views: 258

Answers (2)

Barremian
Barremian

Reputation: 31105

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.

Upvotes: 0

alt255
alt255

Reputation: 3566

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

Upvotes: 1

Related Questions