【发布时间】:2018-08-03 05:42:37
【问题描述】:
我的后端 API http://localhost:8300/api/picture 返回一个字符串,我尝试了以下方法:
(getpicture 在按钮点击时被调用)
方法一:
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>
输出:
发现“调用支持时出现一些错误”(即打印错误)
方法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();
}
输出: 我得到编译器错误:
类型 Promise
<string>不可分配给类型“字符串”。
我错过了什么?
编辑: 我已删除正在打印的自定义错误消息
“找不到图片”
使用console.error(error),因为它造成了我的后端返回此错误的混乱。
打印的错误信息是:
e {headers: t, status: 200, statusText: "OK", url: “http://localhost:8300/api/picture”,正常:假,...} 错误:{错误: SyntaxError:JSON.parse 中位置 0 处的 JSON 中的意外标记 h () 在 XMLHttp...,文本: "https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg"} 标头:t {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} 消息:“解析期间的 Http 失败 http://localhost:8300/api/picture" 名称:"HttpErrorResponse" 确定: 错误状态:200 statusText:“OK”网址: "http://localhost:8300/api/picture"
【问题讨论】:
-
您可以在此处粘贴来自 API 的示例响应吗?
-
@theLearner, "map" 用于转换响应,而不是调用函数(你可以使用 "do")。您在“订阅”中得到响应,因此您的第一种方法是正确的。确定你用的是HttpClient,试试写console.log(error)看看报错
-
@Eliseo 关于错误消息的任何想法:
Type Promise<string> is not assignable to type 'string'.
标签: javascript angular typescript