我正在Angular 4.x中编写一个软件,对于服务处理的每个api请求,需要知道来自其他服务的信息(Id).
我的问题是关于角度模式和良好实践.对于我的具体案例,最好的方法是什么:
1 – 每次需要使用ID信息执行API请求时,使用服务A来呼叫服务B.像这样:
服务A.
@H_404_17@@Injectable() export class AService { // ID public myId: string; [...] }服务B.
@H_404_17@@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.
@H_404_17@@Injectable() export class AService { // ID public myId: string; [...] }服务B.
@H_404_17@@Injectable() export class BService { constructor( private restangular: Restangular,) { } public get(callback: (_: string[]) => void,myId: string) { // Sends the request return this.restangular .all('myrequest') .customGET('',{ myId: myid,}) [...] } [...] }组件C.
@H_404_17@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() { } }解决方法
我已经使用继承来调用另一个服务.我创建了一个Base服务来设置令牌或id信息,如果任何服务需要这些令牌,它们可以很容易地被基本服务扩展.这是一个例子
基础服务
@H_404_17@@Injectable() export class BaseService { public myId: string; [...] }其他服务
@H_404_17@@Injectable() export class OtherService extends BaseService { constructor( private restangular: Restangular,{ myId: this.myid,}) [...] } [...] }我通常使用基本服务来设置身份验证标头来验证apis.