脚本:
-
它们接受一个返回参数,
-
-
他们回报了一个承诺。
这是我推广包装器函数(用于get)的尝试:
public httpGetPromise<T extends any>(endpoint: string, returnType: T): Promise<T> {
const promise: Promise<returnType> = new Promise<returnType>((resolve,reject) => {
this.http.get<returnType>(`${this.endpointBaseUri}+${endpoint})
.toPromise().then((response) => {
resolve(response);
}, (err) => {
reject(response);
});
});
return promise;
}
这在某种程度上简化了它。但我相信一定有更好的办法。
有没有更好的方法来编写这个包装器函数,使它更通用,更适合不同的输入类型?
应用程序的示例代码
Get / Post / Delete
public saveMachine(newMachine: Machine): Promise<Machine> {
const promise: Promise<Machine> = new Promise<Machine>((resolve, reject) => {
this.http.post<Machine>(`${this.endpointBaseUri}/machines`, newMachine).toPromise().then((res) => {
resolve(res);
}, (err) => {
reject(err);
});
});
return promise;
}
public deleteMachine(machine: Machine): Promise<Machine> {
const promise: Promise<Machine> = new Promise<Machine>((resolve, reject) => {
this.http.delete<Machine>(this.endpointBaseUri + `/machines/${machine.id}`)
.toPromise().then((response) => {
resolve(response);
}, (err) => {
reject(err);
});
});
return promise;
}
public getMachinesConfigs(machineId: string): Promise<MachineConfig[]> {
const promise: Promise<MachineConfig[]> = new Promise<MachineConfig[]>((resolve, reject) => {
this.http.get<MachineConfig[]>(`${this.endpointBaseUri}/machines/${machineId}/machineconfigs`
).toPromise().then((response) => {
resolve(response);
}, (err) => {
reject(err);
});
});
return promise;
}
这就是我的建议包装器函数(用于get)调用的样子:
public getMachinesConfig(machineId:string, MachineConfig[]): MachineConfig[] {
const endpoint: string = `/machines/${machineId}/machineconfigs`;
return this.wrapperService.httpGetPromise(endpoint, MachineConfig[]);
}
3.2.4
.
比如:
public promiseFunc(httpMethod:HttpClient,..., data?:any, etc...)
这样,单个函数将处理所有post get和delete承诺。