如何缩小此功能?

时间:2019-06-14 08:29:22

标签: typescript

我想通过删除发送到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();
    });
  }

按原样工作,但我希望它更整洁,更短。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

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

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

您的方法->

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