[英]angular4: unable to obtain response string using httpclient get
My backend API http://localhost:8300/api/picture
returns a string and I have tried following approaches: ( getpicture
is called on button click)我的后端 API http://localhost:8300/api/picture
返回一个字符串,我尝试了以下方法:(单击按钮时调用getpicture
)
Approach 1:方法一:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-auth-success',
templateUrl: './auth-success.component.html',
styleUrls: ['./auth-success.component.scss']
})
export class AuthSuccessComponent implements OnInit {
showImg: boolean = false;
imgUrl: string = "";
constructor(private http: HttpClient) { }
ngOnInit() {
}
getPicture(){
this.http.get("http://localhost:8300/api/picture",{ observe: 'response' })
.subscribe(
res => {
console.log(res);
this.onSuccess(res);
}, error => {
console.error("Some error while calling backed");
});
}
onSuccess(data: any){
this.imgUrl = data;
this.showImg = true;
}
}
And HTML:和 HTML:
<div>
<button (click)="getPicture()">Google Picture</button><br><hr><hr>
<img [src]="imgUrl" *ngIf="showImg">
</div>
Output:输出:
"Some error while calling backed" found (ie error is printed)发现“调用支持时出现一些错误”(即打印错误)
Approach 2:方法二:
getPicture(){
this.http.get("http://localhost:8300/api/picture")
.map((res : Response)=> {
console.log(res); // correct value printed if below line is commented
this.imgUrl = res.text(); // compiler gives error at this line
})
.subscribe();
}
Output: I get compiler error:输出:我得到编译器错误:
Type Promise
<string>
is not assignable to type 'string'.类型 Promise<string>
不可分配给类型 'string'。
What am I missing?我错过了什么?
EDIT: I have removed the custom error message that was getting printed编辑:我已经删除了正在打印的自定义错误消息
"Image not found" “找不到图片”
with console.error(error)
as it was creating a confusion that my backend is returning this error.使用console.error(error)
因为它造成了我的后端正在返回此错误的混乱。 The error message printed is:打印的错误信息是:
e {headers: t, status: 200, statusText: "OK", url: " http://localhost:8300/api/picture ", ok: false, …} error : {error: SyntaxError: Unexpected token h in JSON at position 0 at JSON.parse () at XMLHttp…, text: " https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg "} headers : t {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message : "Http failure during parsing for http://localhost:8300/api/picture " name : "HttpErrorResponse" ok : false status : 200 statusText : "OK" url : " http://localhost:8300/api/picture " e {headers: t, status: 200, statusText: "OK", url: " http://localhost:8300/api/picture ", ok: false, ...} error : {error: SyntaxError: Unexpected token h in JSON在 XMLHttp 的 JSON.parse () 位置 0 处,文本:“ https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg ”} 标头:t {normalizedNames: Map( 0), lazyUpdate: null, lazyInit: ƒ} message : "Http failure during parsing for http://localhost:8300/api/picture " name : "HttpErrorResponse" ok : false status : 200 statusText : "OK" url : " http://localhost:8300/api/图片"
As explained in this answer , Http
was inspired by Fetch API and has classes of same names, though they aren't compatible, because Http
uses observables, and Fetch API uses promises.正如在这个答案中所解释的, Http
灵感来自 Fetch API 并且具有相同名称的类,尽管它们不兼容,因为Http
使用 observables,而 Fetch API 使用承诺。
The implication is that if Response
wasn't imported, global Response
will be used.言下之意是,如果Response
未导入,全球Response
将被使用。 Since Response
is used here only as a type, the problem affects types only.由于这里仅将Response
用作类型,因此问题仅影响类型。 There should be:应该有:
import { Response } from '@angular/http';
This doesn't apply to HttpClient
.这不适用于HttpClient
。 The main difference in the code that uses HttpClient
is that response negotiation is performed with observe
and responseType
options, and .map((res) => res.text())
line should be omitted.使用HttpClient
的代码的主要区别在于,响应协商是使用observe
和responseType
选项执行的,并且应该省略.map((res) => res.text())
行。
Approach 1 uses observe: 'response'
which isn't needed here, but doesn't set responseType
which defaults to json
and results in JSON parse error.方法 1使用observe: 'response'
,这里不需要它,但没有设置默认为json
responseType
并导致 JSON 解析错误。 Approach 2 uses Http
API, while http
is HttpClient
.方法 2使用Http
API,而http
是HttpClient
。
map
isn't a proper place for side effects. map
不是产生副作用的合适位置。 Dummy subscribe()
indicates that an observable is misused here.虚拟subscribe()
表示这里滥用了一个可观察的对象。 If there's no benefit from using observables, a promise may be more convenient option:如果使用 observables 没有任何好处,promise 可能是更方便的选择:
async getPicture(){
try {
this.imgUrl = await this.httpClient.get("http://localhost:8300/api/picture", { responseType: 'text' })
.toPromise();
this.showImg = true;
} catch (e) {
...
}
}
This isn't relevant to original problem, Image not found
.这与原始问题无关, Image not found
。 Backend API responds with an error.后端 API 响应错误。 This has nothing to do with Angular and should be fixed, depending on the backend.这与 Angular 无关,应该修复,具体取决于后端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.