我在服务上有一个处理所有后端请求的方法。与其使用HttpClient编写一大堆不同的调用,我还以为我可以编写一个函数,该函数可以连接到后端并传递参数来处理不同类型的数据。
考虑这个函数
public postRequest(token: string, url: string, body: any, headers: Object = {}) : Observable<any> {
//create new header object
const httpOptions = {
headers: new HttpHeaders()
.set('Authorization', token)
};
//add the headers if any
for(let index in headers){
httpOptions.headers.set(index, headers[index]);
}
//connect to the backend and return the repsonse
return this.http.post( this.config.BASE_SERVER_URL + url, body , httpOptions)
.pipe(
map((res) => {
return res;
}),
catchError(this.handleError)
);
}它工作得很好,只是我希望能够动态地设置响应类型。因此,我可以将方法设置为使用我的模型类型之一。
这就是我想要达到的目标。希望这是有意义的。
map(res: "Attendee") => {}
//or
map(res: typeof(typeInput)) => {}是否可以将pas“动态”类型映射到http map方法,以便将不同的响应映射到我选择的模型?
发布于 2019-02-15 18:27:05
我可以通过使用泛型方法来实现这一点。
你可以用这个方法。
my-own.service.ts
userAuthentication<T>(userName: string, password: string): Observable<T> {
const url = `http://my-own.url`;
const targetData = {
'emailId': userName,
'password': password
};
return this.http.post<CommonResponse<T>>(url, targetData, httpOptions).pipe(
retry(3),
map((data: CommonResponse<T>) => {
if (data.status) {
if (!data.result[0]) {
this.showMessage('You are not authorized for login');
return null;
}
return data.result[0] as T;
}
this.showMessage(data.message);
return null;
}),
tap((userProfile: T) => {
console.log('UserLogin ');
}),
catchError(this.handleError<T>('unable to logged in')));
}CommonResponse模型
export class CommonResponse<T> {
autherizationExpires: string;
autherizationKey: string;
message: string;
result: T | T[];
status: boolean;
}因此,当您像myOwnService.userAuthentication < LoginModel >(...params).subscribe(/ *您的代码*/)一样调用这个方法时,它也会继承到映射中。
如果我不明白你的问题,请告诉我。
https://stackoverflow.com/questions/54714909
复制相似问题