首页 文章

在Angular项目中将Http迁移到HttpClient

提问于
浏览
2

我正在开发一个项目,需要迁移旧Http的所有实例以利用Angular提供的新HttpClient . Async methods are declared within a DataService class like this:

@Injectable()
export class DataService {

  constructor(private http: Http) { }

  async getAsync<T>(resource: string, options?: RequestOptions): Promise<T> {
    return this.http
      .get(resource, options)
      .map((response: Response) => response.json())
      .catch(this.handleError).toPromise();
  }

并在另一个服务类中使用,如下所示:

async getUser() {
  try {
    this.logger.debug('Getting User State...');

    const userInfo = await this.dataService.getAsync<[Type Parameter]>(
      this.constantService.urls.authenticatedUserUri, <RequestOptions>{ withCredentials: true }
    );

    this.logger.debug(JSON.stringify(userInfo));
    this.authorizeUser(userInfo);
  } catch (error) {
    this.logger.debug(error);
  }
}

我知道为了使用HttpClient,我需要在提供DataService类的模块中导入HttpClientModule,然后在服务本身内导入HttpClient并通过类的构造函数注入它 . 我也知道 .map((response: Response) => response.json() ) 行是不必要的,因为JSON现在是默认的响应类型 .

My main question is what to use in place of the RequestOptions object which is no longer supported in the HttpClient module. 我必须使用HttpHeaders和/或HttpParams来代替RequestOptions,但我不确定实现 . <RequestOptions>{ withCredentials: true } 这条线也让我失望了 .

我将继续研究并通过文档来尝试找到合适的解决方案,但我感谢您对此特定问题的任何帮助 . 谢谢!

1 回答

  • 2

    选项不再输入

    只需将 RequestOptions 替换为 any 即可 .

    在文档中,您可以看到以下内容:

    request(first: string|HttpRequest<any>, url?: string, options: {
        body?: any,
        headers?: HttpHeaders|{[header: string]: string | string[]},
        observe?: HttpObserve,
        params?: HttpParams|{[param: string]: string | string[]},
        reportProgress?: boolean,
        responseType?: 'arraybuffer'|'blob'|'json'|'text',
        withCredentials?: boolean,
    } = {}): Observable<any>
    

    如您所见, withCredentials 仍然可用且 options 没有类型

相关问题