我的后端API http://localhost:8300/api/picture
返回一个字符串,我尝试了以下方法:
(getpicture
在按钮单击时调用)
方法 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;
}
}
和 HTML:
<div>
<button (click)="getPicture()">Google Picture</button><br><hr><hr>
<img [src]="imgUrl" *ngIf="showImg">
</div>
输出:
"Some error while calling backed" found (i.e. error is printed)
方法 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();
}
输出: 我收到编译器错误:
Type Promise
<string>
is not assignable to type 'string'.
我错过了什么?
编辑: 我已删除正在打印的自定义错误消息
"Image not found"
与console.error(error)
因为我的后端返回此错误造成了困惑。
打印的错误信息是:
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"
最佳答案
如 this answer 中所述, Http
受到 Fetch API 的启发,并且具有相同名称的类,尽管它们不兼容,因为 Http
使用 observables,Fetch API 使用 Promise。
这意味着如果 Response
未进口,全局 Response
将会被使用。自 Response
此处仅用作类型,该问题仅影响类型。应该有:
import { Response } from '@angular/http';
这不适用于 HttpClient
。使用 HttpClient
的代码的主要区别是通过 observe
执行响应协商和responseType
选项,以及 .map((res) => res.text())
应省略该行。
方法 1 使用 observe: 'response'
这里不需要,但没有设置 responseType
默认为 json
并导致 JSON 解析错误。
方法 2 使用 Http
API,同时http
是 HttpClient
.
map
不是产生副作用的合适地方。假人 subscribe()
表明此处滥用了可观察量。如果使用可观察量没有任何好处,那么 Promise 可能是更方便的选择:
async getPicture(){
try {
this.imgUrl = await this.httpClient.get("http://localhost:8300/api/picture", { responseType: 'text' })
.toPromise();
this.showImg = true;
} catch (e) {
...
}
}
这与原始问题无关,Image not found
。后端 API 响应错误。这与 Angular 无关,应该根据后端进行修复。
关于javascript - Angular 4 : unable to obtain response string using httpclient get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943245/