【问题标题】:How to make this function smaller?如何使这个函数变小?
【发布时间】:2019-06-14 08:29:22
【问题描述】:

我想通过删除发送到 htttp.post 的变量并将它们放入一个数组来优化以下函数。这可能吗?

将变量放在普通数组中,但出现布尔错误。

  getUsers(val) {
    this.spinner.show();
    const options = {
      headers: new HttpHeaders().set('x-access-token', this.currentUser.token),
      responseType: 'blob' as 'json'
    };
    return this.http.post(this.apiRoot + val, { status: this.userAdvanceSearch.status, email: this.userAdvanceSearch.email, filterWithin: this.filterQuery, name: this.userAdvanceSearch.name, userTypeNo: this.authenticationService.getCurrentUserType().userTypeNo }, options).subscribe((res: any) => {
      val === 'pdf' ? this.blob = new Blob([res], { type: 'application/pdf' }) : this.blob = new Blob([res], { type: 'text' });
      const downloadURL = window.URL.createObjectURL(res);
      const link = document.createElement('a');
      link.href = downloadURL;
      val === 'pdf' ? link.download = 'users.pdf' : link.download = 'users.csv';
      link.click();
      window.URL.revokeObjectURL(downloadURL);
      this.spinner.hide();
    });
  }

这可以按原样工作,但如果可能的话,我希望它更简洁。

【问题讨论】:

  • 看起来像 Angular 代码,如果是,为什么不使用服务文件来抽象​​您的 HTTP 请求?

标签: javascript node.js angular typescript ecmascript-6


【解决方案1】:

这样会更好地减少服务的工作量,只使用服务进行 API 调用。在组件中你会订阅并做一些逻辑计算

getUsers(val) {
    const options = {
        headers: new HttpHeaders().set('x-access-token', this.currentUser.token),
        responseType: 'blob' as 'json'
    };

    let data = { status: this.userAdvanceSearch.status, 
        email: this.userAdvanceSearch.email, 
        filterWithin: this.filterQuery, 
        name: this.userAdvanceSearch.name, 
        userTypeNo: this.authenticationService.getCurrentUserType().userTypeNo 
    }

    return this.http.post(this.apiRoot + val, data, options);
}

someMethod() {
    this.spinner.show();
    this.someService.getUsers(val).subscribe((res: any) => {
        val === 'pdf' ? this.blob = new Blob([res], { type: 'application/pdf' }) : this.blob = new Blob([res], { type: 'text' });
        const downloadURL = window.URL.createObjectURL(res);
        const link = document.createElement('a');
        link.href = downloadURL;
        val === 'pdf' ? link.download = 'users.pdf' : link.download = 'users.csv';
        link.click();
        window.URL.revokeObjectURL(downloadURL);
    });
    this.spinner.hide();
}

【讨论】:

    【解决方案2】:

    您可以定义一个类来描述您要发送的数据,例如

    export class DataRequest {
       status: string;
       email:string;
       ...
    }
    

    你的方法 ->

    dataRequest = new DataRequest();
    dataRequest.status = this.userAdvanceSearch.status;
    ...
    return this.http.post(this.apiRoot + val, dataRequest)....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多