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

时间:2018-02-23 07:38:10

标签: javascript angular typescript

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

      }

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

  

Type Promise <string>不能指定为'string'类型。

我错过了什么?

修改 我已删除了正在打印的自定义错误消息

  

“未找到图片”

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

  

e {headers:t,status:200,statusText:“OK”,url:   “http://localhost:8300/api/picture”,ok:false,...}错误:{错误:   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:ƒ}   消息:“解析期间的Http失败   http://localhost:8300/api/picture“name:”HttpErrorResponse“ok:   false status:200 statusText:“OK”url:   “http://localhost:8300/api/picture

1 个答案:

答案 0 :(得分: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无关,应该修复,具体取决于后端。