Angular 4+ Service referencing another useful service practice

I am writing software in Angular 4.x, which for every api request processed by the Service must know information from another service (Id).

My question is this is an Angular sample and good practices. For my specific case, what would be the best approach:

1 - Using service A to call service B every time he needs to execute an API request with identifier information. Like this:

Service A

@Injectable()
export class AService {

  // ID
  public myId: string;

  [...]
}

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

  [...]
}

or

2 - Never call a service from another service and always use the component for the first call to the AService, and then use the value in the BService (and thus have the same code that is replicated every time the API is called (or at least one time for each component using this api call).

Service A

@Injectable()
export class AService {

  // ID
  public myId: string;

  [...]
}

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

}
+4
1

. , , - , .

    @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.

+1

Source: https://habr.com/ru/post/1691272/


All Articles