简体   繁体   English

Angular HttpClient,动态设置地图类型

[英]Angular HttpClient, setting map type dynamically

I have a method on an service to handle all backend requests. 我在服务上有一个方法可以处理所有后端请求。 Instead of writing a whole bunch of different calls using the HttpClient, I thought I might write one single function that could connect to my backend and pass it arguments to handle different types of data. 我以为我可以编写一个可以连接到后端并传递其参数以处理不同类型数据的函数,而不是使用HttpClient编写大量不同的调用。

Consider this function 考虑这个功能

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)
  );
}

It works well except I wanted to be able to set the response type dynamically. 它运行良好,但我希望能够动态设置响应类型。 Thus I could set the method to use one of my model types. 因此,我可以将方法设置为使用我的一种模型类型。

Here's what I'm trying to accomplish. 这就是我要完成的工作。 Hopefully this makes sense. 希望这是有道理的。

map(res: "Attendee") => {}
//or
map(res: typeof(typeInput)) => {}

Is it possible to pas a "dynamic" type to the http map method so I can map the different responses to a model of my choice? 是否可以在http map方法中使用“动态”类型,以便将不同的响应映射到我选择的模型?

I can achieve this by using generic methods. 我可以通过使用通用方法来实现。

you can use this approach. 您可以使用这种方法。

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 model CommonResponse模型

export class CommonResponse<T> {
  autherizationExpires: string;
  autherizationKey: string;
  message: string;
  result: T | T[];
  status: boolean;
}

So, when you call this method like myOwnService.userAuthentication < LoginModel >(...params).subscribe(/ * your codes * /); 因此,当您调用诸如myOwnService.userAuthentication <LoginModel>(... params).subscribe(/ *您的代码* /)这样的方法时, It will inherited to the map as well. 它将也继承到地图。

let me know if I am not get your question. 让我知道我是否没有收到您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM