angular4:无法使用httpclient get获得响应字符串

尝试学习

我的后端APIhttp://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>

输出:

发现“回叫时出错”(即打印错误)

方法二:

 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();

      }

输出:我得到编译器错误:

<string>不能将“类型承诺”分配给“字符串”类型。

我想念什么?

编辑:我已删除正在打印的自定义错误消息

“找不到图片”

console.error(error),因为它是建立一个困惑,我的后台返回此错误。打印的错误信息是:

e {标题:t,状态:200,statusText:“确定”,URL:“ http:// localhost:8300 / api / picture ”,确定:false,...}错误:{错误:SyntaxError:JSON中的意外令牌h在XMLHttp的JSON.parse()位置0处,文本:“ https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg ”}标头:t {normalizedNames:Map( 0),lazyUpdate:null,lazyInit:ƒ}消息:“在解析http:// localhost:8300 / api / picture期间的Http失败”名称:“ HttpErrorResponse” ok:错误状态:200 statusText:“ OK”网址:“ http:// localhost:8300 / api / picture

那将是烧瓶

正如在解释这个答案Http灵感来自于提取API,并具有相同名称的类,虽然他们是不兼容的,因为Http使用观测,并获取API使用的承诺。

这意味着如果Response不导入,Response将使用global 由于Response此处仅用作类型,因此该问题仅影响类型。应该有:

import { Response } from '@angular/http';

这不适用于HttpClient使用的代码的主要区别HttpClient在于,响应协商是使用observeresponseType选项执行的,.map((res) => res.text())应省略行。

方法1使用observe: 'response'此处不需要的方法,但未将responseType默认值设置为json并导致JSON解析错误。方法2使用HttpAPI,而httpis是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无关,应该固定,具体取决于后端。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章