簡體   English   中英

如何從 API 接收 HTML 響應並將其綁定到 Angular 7 中的視圖模板。

[英]How to receive HTML response from an API and bind it to view template in Angular 7.

我的 API 調用的響應是 HTML 文檔,我需要將 html 響應綁定到我的 angular 模板。 我使用下面的可觀察代碼嘗試了它,但沒有運氣。 請任何幫助。

服務方式:

getResults(): Observable<string> {
     return this.http.get<any>('https://stackoverflow.com/questions/tagged/angular');
  }

在組件中訂閱:

ngOnInit() {
    this._apiService.getResults()
    .subscribe(data => {
      this.results = data;
    },
    error => console.log('Error from backend API', +error));
  }

如果我正確理解了這個問題,你會得到 html 代碼,例如:

<div>Some text</div>

你想把它添加到你的模板中。? 所以首先你必須修改你的 get 調用。 默認情況下,獲取 json 響應。 你需要做的是:

getResults(): Observable<string> {
     return this.http.get<string>('https://stackoverflow.com/questions/tagged/angular',{responseType: 'text'});
  }

模板中的第二個:

<div class="one" [innerHtml]="htmlToAdd"></div>

然后在訂閱者中

ngOnInit() {
    this._apiService.getResults()
    .subscribe(data => {
      this.innerHtml = data;
    },
    error => console.log('Error from backend API', +error));
  }

如果這是CORS問題,如果您在本地環境中工作,則必須設置代理。 去創建proxy.conf.json。

{
  "/questions/tagged/angular": {
    "target": "https://stackoverflow.com/questions/tagged/angular",
    "secure": false
  }
}

更改網址:

getResults(): Observable<string> {
     return this.http.get<any>('/questions/tagged/angular');
  }

並使用ng serve --proxy-config proxy.conf.json運行您的應用程序

Cors 的意思是,如果您嘗試訪問https://stackoverflow.com/questions/tagged/angular ,則僅當窗口 URL 為https://stackoverflow.com時才允許您發出該請求。 發出請求時您在瀏覽器中看到的 URL 稱為origin 當您從 localhost 請求時,它將被阻止,因為localhosthttps://stackoverflow.com是不同的。 這由名為access-control-allow-origin的響應頭access-control-allow-origin 這將由您正在訪問的特定站點設置。 我們無法改變這一點。 您可以在MDN-CORS閱讀更多相關信息。

因此,出於開發目的,您可以設置一個簡單的本地服務器來返回一個 html 文件。 或者嘗試訪問一個沒有設置access-control-allow-origin標志的站點。

例如,Mozilla 站點允許所有人訪問,因此如果您嘗試從stackoverflow.com更改為https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS ,它將起作用。

您可以在網絡選項卡中檢查站點是否允許交叉訪問。 見下圖。 如果它的 * all 被允許,或者只允許提到的 urls 將被允許。

訪問控制允許來源

另請注意,angular 默認將所有請求視為json 如果您正在閱讀其他類型,例如html ,則需要指定使用{responseType: 'text'}作為第二個參數。

this.http.get('https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS', {responseType: 'text'})
  .subscribe(data => {
    console.log(data);
  }, error => {
    console.log(error);
  });;

參見Stackblitz 現場示例

暫無
暫無

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

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