【问题标题】:Angular 4+ Service referencing another service good practiceAngular 4+ Service 引用了另一个服务的良好实践
【发布时间】:2018-06-05 18:48:54
【问题描述】:

我正在用 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 - 永远不要从另一个 Service 调用 Service,始终使用组件首先调用 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() {
  }

}

【问题讨论】:

  • “最佳实践”问题通常属于离题类别。除了 AService myId 之外,是否有可能使用任何 id 调用 BService get?回答这个问题,你就会回答你自己的问题。
  • 是和不是。对于该 ID,它将始终是 AService myId,但它可能需要从其他服务调用其他 ID,但并非总是如此。

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


【解决方案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,
      })
    [...]
  }

  [...]
}

我一般使用base service来设置认证头来认证api。

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 2020-08-17
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多