簡體   English   中英

angular4:無法使用 httpclient get 獲取響應字符串

[英]angular4: unable to obtain response string using httpclient get

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

輸出:

發現“調用支持時出現一些錯誤”(即打印錯誤)

方法二:

 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 : {error: SyntaxError: Unexpected token h in JSON在 XMLHttp 的 JSON.parse () 位置 0 處,文本:“ https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg ”} 標頭: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/圖片"

正如在這個答案中所解釋的, Http靈感來自 Fetch API 並且具有相同名稱的類,盡管它們不兼容,因為Http使用 observables,而 Fetch API 使用承諾。

言下之意是,如果Response未導入,全球Response將被使用。 由於這里僅將Response用作類型,因此問題僅影響類型。 應該有:

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

這不適用於HttpClient 使用HttpClient的代碼的主要區別在於,響應協商是使用observeresponseType選項執行的,並且應該省略.map((res) => res.text())行。

方法 1使用observe: 'response' ,這里不需要它,但沒有設置默認為json responseType並導致 JSON 解析錯誤。 方法 2使用Http API,而httpHttpClient

map不是產生副作用的合適位置。 虛擬subscribe()表示這里濫用了一個可觀察的對象。 如果使用 observables 沒有任何好處,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 無關,應該修復,具體取決於后端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM