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

问题描述 投票:2回答:1

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

输出:

找到“调用后台时出现一些错误”(即打印错误)

方法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>不能分配给'string'类型。

我错过了什么?

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

“图片未找到”

console.error(error)因为它造成混乱,我的后端正在返回此错误。打印的错误消息是:

e {headers:t,status:200,statusText:“OK”,url:“http://localhost:8300/api/picture”,ok:false,...}错误:{error:SyntaxError:JSON.parse()位置0的JSON中出现意外的令牌h XMLHttp ...,text:“https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg”} headers:t {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} message:“解析http://localhost:8300/api/picture时的Http失败”名称:“HttpErrorResponse”ok:false status:200 statusText :“好的”网址:“http://localhost:8300/api/picture

javascript angular typescript
1个回答
2
投票

正如在this answer中所解释的那样,Http的灵感来自Fetch API并且具有相同名称的类,尽管它们不兼容,因为Http使用了observable,而Fetch API使用了promises。

这意味着如果没有进口Response,将使用全球Response。由于Response仅在此处用作类型,因此该问题仅影响类型。应该有:

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

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

方法1使用observe: 'response',这里不需要,但不设置responseType,默认为json并导致JSON解析错误。方法2使用Http API,而httpHttpClient

map不适合副作用。假的subscribe()表示在这里滥用了一个观察者。如果使用observable没有任何好处,承诺可能是更方便的选择:

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无关,应该修复,具体取决于后端。

© www.soinside.com 2019 - 2024. All rights reserved.