Angular 4+ Service引用了另一种服务良好实践

ali*_*ody 5 oop model-view-controller components typescript angular

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

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

1-每次需要使用ID信息进行API请求时,使用服务A调用服务B。像这样:

服务A

@Injectable()
export class AService {

  // ID
  public myId: string;

  [...]
}
Run Code Online (Sandbox Code Playgroud)

服务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,
      })
    [...]
  }

  [...]
}
Run Code Online (Sandbox Code Playgroud)

要么

2-切勿从另一个服务调用服务,并且始终使用组件先调用AService,然后使用BService上的值(这样,每次进行API调用时,都将复制相同的代码(或至少每次调用一次)使用该api调用的组件)。

服务A

@Injectable()
export class AService {

  // ID
  public myId: string;

  [...]
}
Run Code Online (Sandbox Code Playgroud)

服务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,
      })
    [...]
  }

  [...]
}
Run Code Online (Sandbox Code Playgroud)

成分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() {
  }

}
Run Code Online (Sandbox Code Playgroud)

Vik*_*iya 1

我已经使用继承来调用另一个服务。我创建了一个基础服务来设置令牌或 ID 信息,如果任何服务需要这些令牌,它们可以轻松地通过基础服务进行扩展。这是一个例子

基础服务

    @Injectable()
export class BaseService {

  public myId: string;

  [...]
}
Run Code Online (Sandbox Code Playgroud)

其他服务

@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,
      })
    [...]
  }

  [...]
}
Run Code Online (Sandbox Code Playgroud)

我通常使用基本服务来设置身份验证标头来对 api 进行身份验证。