Angular 4+服务引用了另一项服务良好做法

时间:2017-12-23 13:37:41

标签: angular typescript oop model-view-controller components

我正在Angular 4.x中编写一个软件,对于服务处理的每个api请求,需要知道来自其他服务的信息(Id)。

我的问题是关于角度模式和良好做法。对于我的具体案例,最好的方法是什么:

1 - 每次需要使用ID信息执行API请求时,使用服务A来呼叫服务B.像这样:

服务A

@Injectable()
export class AService {

  // ID
  public myId: string;

  [...]
}

服务B

@Injectable()
export class BService {

  constructor(
    private restangular: Restangular,
    private aservice: AService,
  ) { }

  public get(callback: (_: string[]) => void) {
    // Sends the request
    return this.restangular
      .all('myrequest')
      .customGET('', {
        myId: this.aservice.myid,
      })
    [...]
  }

  [...]
}

2 - 永远不要从另一个服务调用服务,并始终使用该组件首先调用AService,然后使用BService上的值(因此每次进行API调用时都会复制相同的代码(或至少一个)使用该api调用的每个组件的时间。)

服务A

@Injectable()
export class AService {

  // ID
  public myId: string;

  [...]
}

服务B

@Injectable()
export class BService {

  constructor(
    private restangular: Restangular,
    private aservice: AService,
  ) { }

  public get(callback: (_: string[]) => void, myId: string) {
    // Sends the request
    return this.restangular
      .all('myrequest')
      .customGET('', {
        myId: myid,
      })
    [...]
  }

  [...]
}

组件C

export class CComponent implements OnInit {

  // List of api returned strings
  public apiList: string[] = [];

  constructor(
    private aservice: AService,
    private bservice: BService
  ) {
    this.bservice.get(result => {
      this.apiList = result;
    }, this.aservice.myId);
  }

  ngOnInit() {
  }

}

1 个答案:

答案 0 :(得分:1)

我已经使用继承来调用另一个服务。我创建了一个Base服务来设置令牌或id信息,如果任何服务需要这些令牌,它们可以很容易地被基本服务扩展。这是一个例子

基本服务

    @Injectable()
export class BaseService {

  public myId: string;

  [...]
}

其他服务

@Injectable()
export class OtherService extends BaseService {

  constructor(
    private restangular: Restangular,

  ) { }

  public get(callback: (_: string[]) => void) {
    // Sends the request
    return this.restangular
      .all('myrequest')
      .customGET('', {
        myId: this.myid,
      })
    [...]
  }

  [...]
}

我通常使用基本服务来设置身份验证标头以验证apis。

相关问题