首页 > 解决方案 > Angular 将 HTML 响应数据显示到视图中

问题描述

您好,我是 Angular 的新手,我无法弄清楚在下面的组件中显示 html 响应数据是我的代码,请有人帮忙。谢谢

data.Service.ts(这里我调用一个返回一些 html 的 API 服务)

getLibrary() {return this.http.get('http://localhost:8000/api/user/library');}

库.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-library',
  templateUrl: './library.component.html',
  styleUrls: ['./library.component.scss']
})
export class LibraryComponent implements OnInit {

  library: any;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getLibrary().subscribe(
      data => this.library = data 

    );



  }

}

库.component.html

{{library}}

错误

core.js:14576 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/api/user/library", ok: false, …}
error: {error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "<div style="display:block" class="libContainer lib…            
↵           </div>
↵
↵
↵&lt;/div>
↵
↵
↵
↵
↵
↵
↵
↵
↵"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8000/api/user/library"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8000/api/user/library"
__proto__: HttpResponseBase

标签: javascriptangular6

解决方案


返回的数据类型是文本,您可以像这样使用

 ngOnInit() {
        this.data.getLibrary().subscribe(
          (data:(any)) => this.library = data 

        );

在视野中

<div [innerHTML]="library"></div>

推荐阅读