处理打字稿代码中的代码重复

时间:2017-09-06 11:49:38

标签: typescript refactoring dry single-responsibility-principle

我正在重构一个写得不好的Angular2代码,它具有以下服务方法:

  fooServiceName(body): Observable<any> {
    let headers = new Headers();
    this.loginService.writeAuthToHeaders(headers);
    return this.http.put(this.loginService.url() + '/url', body, { headers: headers })
    .map(response => response.json());
  }

  barResource(body): Observable<any> {
    let headers = new Headers();
    this.loginService.writeAuthToHeaders(headers);
    return this.http.post(this.loginService.url() + '/url', body, { headers: headers })
    .map(response => response.json());
  }

我看到以下几行在许多地方重复使用:

let headers = new Headers();
this.loginService.writeAuthToHeaders(headers);

我想写一个单独的方法来调用这些行,但问题是项目的新手必须记得调用该方法,有没有更好的方法?

更新

添加缺少的方法定义:

  /** function to write username and password to local storage of browser*/
  public writeAuthToHeaders(headers: Headers): void {
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Basic ' + btoa(getUsername() + ':' + this.getPassword()));
  }

2 个答案:

答案 0 :(得分:1)

如果类几乎相同,您可以编写复杂类型,并将差异传递给constructor。我写了以下作为例子:

<强> Generic.Service.ts

import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';

export class GenericService<T> {
    protected http: Http;

    constructor(private TCreator: { new (properties: any): T }, private url: string) {}

    public get(id: number): Observable<T> {
        return this.requestSingle(`${id}`);
    }

    public getAll(): Observable<T[]> {
        return this.requestMultiple('/all.json');
    }

    private requestSingle(addedUrl?: string): Observable<T> {
        return this.request(addedUrl)
        .map((response: Response) => new this.TCreator(response.json()));
    }

    private requestMultiple(addedUrl?: string): Observable<T[]> {
        return this.request(addedUrl)
        .map((response: Response) => {
            const results: any = response.json();
            for (let i = 0; i < results.length; i++) {
                results[i] = new this.TCreator(results[i]);
            }
            return results;
        });
    }

    private request(addedUrl?: string): Observable<any> {
        return this.http.get(this.url + (addedUrl ? addedUrl : ''));
    }
}

使用示例:

<强> Vegetable.Service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import { GenericService } from './generic.service';
import { Vegetable } from '../app.component';

@Injectable()
export class VegetableService extends GenericService<Vegetable> {
    constructor(protected http: Http) {
        super(Vegetable, '/vegetables');
    }
}

<强> Vegetable.ts

interface IVegetable {
  id: number;
  name: string;
  type: string;
}

export class Vegetable implements IVegetable {
  public id: number;
  public name: string;
  public type: string;

  constructor(properties: IVegetable) {
    this.id = properties.id;
    this.name = properties.name;
    this.type = properties.type;
  }
}

<强> Some.Component.ts

import { Component, OnInit } from '@angular/core';

import { VegetableService } from './services/vegetable.service';
import { IVegetable } from '.components/vegetable.component';

@Component({
  selector: 'some-component',
  templateUrl: './some.component.html'
})
export class SomeComponent implements OnInit {
  public vegetables: IVegetable[] = [];

  constructor(private vegetableService: VegetableService) { ... }

  public ngOnInit(): void {
    ...
    this.vegetableService.getAll().subscribe((result) => this.vegetables = result);
    ...
  }
}

答案 1 :(得分:0)

最好是创建一个共享所有常用方法的Gloabl service,让我们假设您的问题

您可以为整个应用创建全局方法来执行此类

相同的任务
 getHeaders(){
    let headers = new Headers();
    this.loginService.writeAuthToHeaders(headers);
    return headers;
 }

 fooServiceName(body): Observable<any> {
    return this.http.put(this.loginService.url() + '/url', body, { headers: this.getHeaders() })
    .map(response => response.json());
  }

  barResource(body): Observable<any> {
    return this.http.post(this.loginService.url() + '/url', body, { headers: this.getHeaders() })
    .map(response => response.json());
  }

还尝试为CRUD操作创建一些全局方法,以便将来使用时尝试使用它们而不是每次都创建新的 只需要将变量作为urldata等参数传递。