angular - 在 Angular 项目中将 Http 迁移到 HttpClient

标签 angular http httpclient

我正在开展一个项目,该项目需要迁移旧 Http 的所有实例以利用 Angular 提供的新 HttpClient。 异步方法在 DataService 类中声明如下:

@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 并通过类的构造函数注入(inject)它。我也知道 .map((response: Response) => response.json() ) 行是不必要的,因为 JSON 现在是默认的响应类型。

我的主要问题是使用什么来代替 HttpClient 模块不再支持的 RequestOptions 对象。我假设我将不得不使用 HttpHeaders 和/或 HttpParams RequestOptions,但我不确定实现。线路<RequestOptions>{ withCredentials: true }也让我失望。

我将继续研究并仔细阅读文档以尝试找到合适的解决方案,但我非常感谢对这个特定问题的任何帮助。谢谢!

最佳答案

不再输入选项

只需将 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 没有类型

关于angular - 在 Angular 项目中将 Http 迁移到 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47204686/

相关文章:

c# - 我可以避免http质询响应吗?

javascript - 数组填充后如何加载页面?

database - 如何检索数据并将其存储到数据库中?

java - 本地路径的 OSGi httpService.registerResources()

c++ - 如何使用 Android ndk 进行 HTTP 请求

visual-studio - Http到https。 IIS还是Visual Studio?

java - 使用 Apache 的 HttpClient 时是否需要指定超时?

Angular 路由器在创建应用程序组件之前寻找导出

angular - 什么时候使用 Ngzone.run()?

asp.net-core - 单例 HttpClient 是否在 X 分钟后接收到新的 HttpMessageHandler