Typescript / Angular 5-如何确保使用功能参数?

时间:2018-08-27 15:39:19

标签: angular typescript binding this

我正在使用Angular 5和Ionic 4编写组件。

我想传递Refresher事件,以便在用户刷新时隐藏刷新微调器,而finally函数可以隐藏微调器。

这是我的代码:

export class UserInfoService {

    constructor(private employeeService: EmployeeService) {
        this.handleSuccess = this.handleSuccess.bind(this);
        this.processData = this.processData.bind(this);
        this.handleFinally = this.handleFinally.bind(this);
    }

    getEmployeeInfo(event?: Refresher) {

        // console.log(event);

        return this.employeeService
            .getEmployeeInfo()
            .map(this.handleSuccess)
            .finally(this.handleFinally);
            // .finally(() => {
            //     if (event != null) {
            //         console.log(' event ', event);
            //         event.complete();
            //     }
            // });
    }

    handleFinally() {
        console.log(' handle finally ', event);

        if (event != null) {
            console.log(' event ', event);
            event.complete();
        }
    }

注释掉的代码可以很好地工作,但是不必使用匿名函数会很好。将其绑定到构造函数后,它将处理其他事件。

2 个答案:

答案 0 :(得分:2)

必须提供event值。将其设为handleFinally的参数呢?仍然需要匿名函数,但它现在更短了,不会降低可读性:

export class UserInfoService {
  constructor(private readonly employeeService: EmployeeService) {
      this.handleSuccess = this.handleSuccess.bind(this);
      this.processData = this.processData.bind(this);
  }

  getEmployeeInfo(event?: Refresher) {
      // console.log(event);

      return this.employeeService
          .getEmployeeInfo()
          .map(this.handleSuccess)
          .finally(() => this.handleFinally(event));

  }

  handleFinally(event?: Refresher) {
      console.log(' handle finally ', event);

      if (event) {
          console.log(' event ', event);
          event.complete();
      }
  }
}

答案 1 :(得分:1)

您仍然可以将数组函数与函数变量一起使用,如下所示:

location /ws/streams/ {
  rewrite \/ws\/streams\/(\d+) /streams/$1?token=TOKEN break;
  proxy_pass https://www.stream.com;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "Upgrade";
}