Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angular8上从HTTP迁移到HTTPClient_Angular_Xmlhttprequest_Httpclient - Fatal编程技术网

在Angular8上从HTTP迁移到HTTPClient

在Angular8上从HTTP迁移到HTTPClient,angular,xmlhttprequest,httpclient,Angular,Xmlhttprequest,Httpclient,我正在迁移我的Angular以使用新的HttpClient,但是为了达到与Http相同的效果,我遇到了一些问题 我将在评论中加入我尝试过的内容: 从'@angular/core'导入{Injectable,OnDestroy}; 从“rxjs”导入{Observable}; 从“rxjs/operators”导入{map}; 从'@angular/Http'导入{Http,Header}; //从'@angular/common/http'导入{HttpClient,HttpHeaders,Ht

我正在迁移我的Angular以使用新的HttpClient,但是为了达到与Http相同的效果,我遇到了一些问题

我将在评论中加入我尝试过的内容:

从'@angular/core'导入{Injectable,OnDestroy};
从“rxjs”导入{Observable};
从“rxjs/operators”导入{map};
从'@angular/Http'导入{Http,Header};
//从'@angular/common/http'导入{HttpClient,HttpHeaders,HttpParams};
从“../app.component”导入{Environment};
//所有其他组件进口
@可注射()
导出类CompanyService实现OnDestroy{
私有url=Environment.origin;
私有标头=新标头({
//私有标头=新的HttpHeader({
“接受”:“应用程序/cp+json”,
“内容类型”:“应用程序/json”
});
构造函数(私有http:http){}
//构造函数(私有http:HttpClient){}
buscarEmpresas(pesquisa:string):可观察{
返回this.http.get(`${this.url}/companys/${pesquisa}/search`,{headers:this.headers})
.pipe(map((response)=>response.json().response));
}
/*返回this.http.get(`${this.url}/companys/${pesquisa}/search`,{headers:this.headers,注意:'response'})
*.pipe(map(res=>res));
*--还尝试在标头上停止--返回this.httpClient.get(`${this.url}/companys/${pesquisa}/search`,{headers:this.headers}*/
getEmpresaByUrlLink(urlLink:string):可观察{
返回this.http.get(`${this.url}/companys/link/${urlink}`,{headers:this.headers})
.pipe(map((response)=>newreturno(response.json());
}
/*返回this.http.get(`${this.url}/companys/link/${urlink}`,{headers:this.headers})
*.pipe(map((response)=>new returno(response))*/

进行这些更改时,第一个方法不返回任何内容,第二个方法返回500。

对于httpClient,您不需要添加头(缺陷是json),也不需要使用response.json()(响应仍然是json。如果您的API返回字符串(这不正常),则需要使用
{response:text}
,请参阅,但我告诉您,根据我的经验,您需要这样做是不正常的。谢谢Eliseo!!我试图从选项中删除标题,但它不起作用。我还试图删除
.pipe(map((response)=>response.json().response))
,但它不起作用:(使用
console.log(response)检查您收到了什么)
在subscribe函数中。如果您收到类似'res:{…}'的消息,您可以映射
map((response)=>response.res)
。对于第一种方法,console.log返回
response:Array(10)
,它甚至可以排除选项(如您所说)并包括
.pipe(map((response)=>response.response)
\o/。我不太明白为什么,但它起了作用。第二个方法(返回一个对象),如果我删除标题,浏览器会抱怨。它仍然返回500