我正在用 Angular 4.x 编写一个软件,对于服务处理的每个 API 请求,都需要知道来自另一个服务的信息(一个 Id)。
我的问题是关于 Angular 模式和良好做法。对于我的具体情况,最好的方法是什么:
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 - 切勿从另一个服务调用服务,始终使用组件首先调用 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() {
}
}
最佳答案
我已经使用继承来调用另一个服务。我制作了一个基本服务来设置 token 或 ID 信息,如果任何服务需要这些 token ,它们可以很容易地由基本服务扩展。这是一个例子
基础服务
@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,
})
[...]
}
[...]
}
我通常使用基本服务来设置身份验证 header 以对 api 进行身份验证。
关于Angular 4+ 服务引用了另一个服务良好实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952966/