0

I'm doing some base classes to do common things and then call overridden methods in the child classes.

In the code bellow, I need to call this.doSomethingElse only after the user is update by user service.

this is in the base class:

public onSubmit() {
    this.beforeSubmit();
    this.submitForm().subscribe(() => {
      this.afterSubmit();
    });
  }

this is in the child class:

  public submitForm(): Observable<User> {
    this.userServices.update(formValues).subscribe((user: User) => {
      this.someChildAction();
      return ??? ?
    });
    return ????
  }

I'm not sure what to code in the ???? lines.

2
  • Have a look at my answer and try to avoid nested subscriptions. Commented Feb 13, 2019 at 23:35
  • @profanis, I can't use the first answer because I need to do some actions after the service update. The second answer calls doSomethingElse that child class does not know. I made some update in the question. Commented Feb 14, 2019 at 0:51

2 Answers 2

1

Return the observable from submitForm method without subscribing. You can then concat the observable using the concatMap operator.

public onSubmit() {
    this.doSomething();
    this.submitForm().concatMap(this.doSomethingElse.bind(this)).subscribe(() => {

    });
  }
 public submitForm(): Observable<User> {
    return this.userServices.update(formValues);
  }

OR

public onSubmit() {
    this.doSomething();
    this.submitForm().subscribe(() => {

    });
  }


  public submitForm(): Observable<User> {
    this.userServices.update(formValues).pipe(
      concatMap(this.doSomethingElse.bind(this)) // <-- the input of the doSomethingElse will be the response of the *update* method
     ).subscribe((user: User) => {
      // here you will have the response of the doSomethingElse
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

0

I accomplished this creating in the child class the afterSubmit() method, like this:

afterSubmit(user) {
  //do child stuff here
  super.afterSubmit(user);
}

submitForm(): Observable<Object> {
  return this.userServices.update(formValues);
}

in base class:

public onSubmit() {
  this.beforeSubmit();
  this.submitForm().subscribe(data => {
    this.afterSubmit(data);
  });
}

public afterSubmit(data) {
  //my common stuff here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.