I'm writing a software in Angular 4.x that, for every api request handled by the Service, needs to know the an information from another service (an Id).
My question, is about angular pattern and good practices. For my specific case, what would be the best approach:
1 - Using the Service A to call the Service B every time he needs to do the API Request with the ID 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 to first call the AService and then use the value on the BService (and thus having the same code replicated everytime an API call is made (or at least, one time for each component using that 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,
})
[...]
}
[...]
}
Component 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() {
}
}
I have used inheritance to call another service. I made one Base service to set token or id information and if any service needs these tokens they can easily be extented by the base service. Here is an example
Base Service
@Injectable()
export class BaseService {
public myId: string;
[...]
}
Other Service
@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,
})
[...]
}
[...]
}
I generally use base service for setting authentication headers to authenticate apis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With