0
votes

I have two sequential http requests in which I send some data to my backend to create a Customer (think of this like a group) and then from the returned data from the first request I create a new user that belongs to this Customer / group. I'm using a modal window with a form to collect the data, on submit after the sequential requests are finished I close the modal window..

This is my method to save the collected data and create the Customer and User, notice the two nested .subscribes... not the best implementation, I want to prevent a "pyramid of doom". Here is my original...

public onSave(): void {}
  const customerData = this.dialogForm.getRawValue();
  const newUser: any = {
    Email: customerData.Email,
    IsActive: true,
    ResetPassword: false,
    Roles:[]
  };

  // add a new customer
  this.customersService.addCustomer(customerData).subscribe((res: any) => {
    newUser.ClientID = res.ID;
    // create the user
    this.usersService.create(newUser).subscribe(() => this.dialogRef.close(false));
  });
}

now I want to refactor the nested .subscribes. I think I need to use .pipe, mergeMap and do... I wrote this...

// add a new customer
this.customersService.addCustomer(customerData).pipe(
      mergeMap(res => {
        newUser.ClientID = res.ID;
        return <Observable<any>> this.usersService.create(newUser)
      }
    ).do(() => this.dialogRef.close(false)));

This obviously isn't going to work. I'm also getting the following TS error from my IDE

Error:(108, 7) TS2684:The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.

Can someone help me work this out? If I need to reword my question, or something is missing please let me know.

1
what line is 108? - pixelbits
I don't really see anything wrong with your attempt that would cause that error, to be honest (saying this after having written an answer already anyway :-) ) - Ingo Bürk

1 Answers

0
votes

You can use

this.customersService.addCustomer(customerData)
  .map(customer => {
    return {...newUser, ClientID: customer.ID};
  })
  .switchMap(user => this.usersService.create(user))
  .subscribe(() => this.dialogRef.close(false));

Or, if you prefer pipeable operators:

this.customersService.addCustomer(customerData).pipe(
  map(customer => {
    return {...newUser, ClientID: customer.ID};
  }),
  switchMap(user => this.usersService.create(user))
).subscribe(() => this.dialogRef.close(false));