打字稿可观察的继承

时间:2019-02-13 22:59:18

标签: angular typescript

我正在做一些基类来做一些普通的事情,然后在子类中调用重写的方法。

在下面的代码中,仅在用户通过用户服务更新后才需要调用this.doSomethingElse

这在基类中:

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

这在子类中:

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

我不确定在????行中要编码什么。

2 个答案:

答案 0 :(得分:1)

通过submitForm方法返回可观察值,而无需订阅。然后,您可以使用concatMap运算符连接可观察对象。

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
    });
  }

答案 1 :(得分:0)

我在子类中完成了afterSubmit()方法的创建,如下所示:

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

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

在基类中:

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

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