【问题标题】:Migrating project from angular 5 to 8 problems with Response -> HttpResponse使用 Response -> HttpResponse 将项目从 Angular 5 迁移到 8 问题
【发布时间】:2020-01-14 02:10:41
【问题描述】:

显然您需要在迁移之前手动更改 Http 因为@angular/http 消失了,取而代之的是@angular/common/http,所有的类都发生了一些变化。

public getData<T>(pathMock: string, pathApi: string): Observable<T> {
    let base: string = (this.getMockIdx()) ? `${AppGlobal.BASE_URL}` : `${AppGlobal.API_URL}`;
    let path: string = (this.getMockIdx()) ? `${pathMock}` : pathApi;
    let url: string = `${base}${path}`;
    return this.http.get(
        url
    ).map((response:  HttpResponse<any>) => {
        let result: T = response;
        return result;
    });
}

这就是我将Response 更改为HttpResponse&lt;any&gt; 的内容(我放了任何东西,因为我只是想让它工作,但我不知道该放什么)。

这会触发以下错误消息:

"...不能分配给'T'类型的约束"

但如果我更改 T,它会变得更加混乱:

回答后更新:

return this.http.get<any>(`${AppGlobal.API_URL}my/api/auth/refresh/tokens`,
  this.getRequestOptions()).pipe(
  map((data: any) => {
      return this.decryptToken(data);
    }
  ));

使用第二个传递的参数也有一个错误: "标头类型的参数:标头不可分配给...

这是怎么回事?

【问题讨论】:

  • 请不要编辑问题只是,因为答案不起作用。您可以评论相应的答案本身。
  • 您的答案有效(我首先使用了您的答案,它与地图导入一起使用,然后 AJT 回答并且他的解释和详细程度客观上更好)我扩大问题的原因是我在那里意识到更深入,一些更详细的案例。

标签: angular typescript http rxjs


【解决方案1】:

实际上你用HttpClient得到的不是HttpResponse,但是HttpClient已经解析了你的响应,所以你得到的是一个匿名对象。我看到您使用的是any。不惜一切代价避免这种情况,输入您的数据,让您的生活更轻松。但在这里,我将使用any,因为您还没有输入您的数据。与其他答案一样,如果您还没有使用可管道运算符,请更新 rxjs。此外,我认为实际使用 map 没有任何用处,因为您没有对 map 中的数据做任何事情,但如果您这样做,它应该看起来像:

import { map } from 'rxjs/operators';

// ...

// replace 'any' with your type, for example an interface
return this.http.get<any>('url').pipe(
  map((data: any) => {
    return data;
  }
)

【讨论】:

  • 谢谢。我已经给你标记了一个答案,但是我发现了一个稍微不同的语法,我传递了我想象的身体参数,它给了我一个错误。在这种情况下正确的语法是什么? (我已经用这个代码段更新了我的问题)
  • @tatsu,你也有打字问题。 Http 使用了Headers,而HttpClient 使用了HttpHeaders,所以import { HttpHeaders } from '@angular/common/http' 并将Headers 替换为HttpHeaders。请记住,HttpHeaders 与 Headers 不同,是不可变的,因此请确保设置它们 correctly :)
  • 谢谢,嗯,它在同一个文件中,并且头文件根本没有被导入(但是 tslint,JS 解释器似乎对这个事实很好)......
  • 我建议您整体阅读HttpClient 文档,因为您正在从Http 更新到HttpClient,因此您可能会遇到一些其他问题。但无论如何,你解决了标题问题吗? :)
  • no 这个头文件仍然被我的 IDE 认为是不正确的
【解决方案2】:

利用pipe() 链接其他RxJS 运算符,在本例中为map()

return this.http.get('url').
   pipe(
      map((response:  HttpResponse<any>) => {
         return response;
      })
   );

【讨论】:

  • 您是否导入了map()?使用import { map } from 'rxjs/operators';
猜你喜欢
  • 2017-04-24
  • 2019-05-19
  • 2016-10-02
  • 2014-02-14
  • 1970-01-01
  • 2020-01-13
  • 2019-05-18
  • 1970-01-01
  • 2015-01-04
相关资源
最近更新 更多