javascript - Angular 4 : unable to obtain response string using httpclient get

标签 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>

输出:

"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,同时httpHttpClient .

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/

相关文章:

javascript - 羽化边缘椭圆 p5.js

javascript - 无法让 jasmine.any(Function) 工作

javascript - Webpack:如何为 "webpack"创建一个加载器,它需要一个依赖数组?

php - 在 JavaScript 数组中包含项目

Angular:延迟加载模块不调用 InjectionToken 工厂

angular - 使用Docker在AWS EC2中进行Spring Boot微服务部署

angular - 类型 'string' 不可分配给类型 'ArrayBuffer | ArrayLike<number> | SharedArrayBuffer'

Angular 通用: Splitting project [solution for old or complex project]

javascript - 在 API 调用 NgRx Angular 之前检查商店

Angular 库 ng-packagr 不会用相对路径替换 tsconfig 路径