【发布时间】: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 调用 BServiceget?回答这个问题,你就会回答你自己的问题。 -
是和不是。对于该 ID,它将始终是 AService myId,但它可能需要从其他服务调用其他 ID,但并非总是如此。
标签: angular typescript oop model-view-controller components