简体   繁体   English

如何从 API 接收 HTML 响应并将其绑定到 Angular 7 中的视图模板。

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

my API call's response is HTML document and I need to bind the html response to my angular's template.我的 API 调用的响应是 HTML 文档,我需要将 html 响应绑定到我的 angular 模板。 I tried it using below observable code and no luck.我使用下面的可观察代码尝试了它,但没有运气。 Any help please.请任何帮助。

Service method:服务方式:

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

Subscribe in the component:在组件中订阅:

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

If I understend the problem correctly in response you get html code for example:如果我正确理解了这个问题,你会得到 html 代码,例如:

<div>Some text</div>

And you want to add that inside of your template.?你想把它添加到你的模板中。? So first of all you have to modify your get call.所以首先你必须修改你的 get 调用。 Get, by default, expect the json in response.默认情况下,获取 json 响应。 What you have to do is this:你需要做的是:

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

and second in the template:模板中的第二个:

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

and then in the subscriber然后在订阅者中

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

if this is a CORS problem you have to set the proxy if you work in local environment.如果这是CORS问题,如果您在本地环境中工作,则必须设置代理。 Go and create proxy.conf.json.去创建proxy.conf.json。

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

change the url:更改网址:

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

and the run your app with ng serve --proxy-config proxy.conf.json并使用ng serve --proxy-config proxy.conf.json运行您的应用程序

What Cors means that, if you try to access say https://stackoverflow.com/questions/tagged/angular , you are only allowed to make that request only when window URL is https://stackoverflow.com . Cors 的意思是,如果您尝试访问https://stackoverflow.com/questions/tagged/angular ,则仅当窗口 URL 为https://stackoverflow.com时才允许您发出该请求。 The URL you see in your browser while making a request is called origin .发出请求时您在浏览器中看到的 URL 称为origin When you request from localhost, it will get blocked, since localhost and https://stackoverflow.com are different.当您从 localhost 请求时,它将被阻止,因为localhosthttps://stackoverflow.com是不同的。 And this is controlled by a response header called access-control-allow-origin .这由名为access-control-allow-origin的响应头access-control-allow-origin This will be set by that particular site which you are visiting.这将由您正在访问的特定站点设置。 We cannot change this.我们无法改变这一点。 You can read more about this at MDN - CORS .您可以在MDN-CORS阅读更多相关信息。

So for development purpose you can setup a simple local server to return a html file.因此,出于开发目的,您可以设置一个简单的本地服务器来返回一个 html 文件。 Or try accessing a site, which doesnt set access-control-allow-origin flag.或者尝试访问一个没有设置access-control-allow-origin标志的站点。

For example, Mozilla site, allows access from all, hence if you try changing from stackoverflow.com to https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS it will work.例如,Mozilla 站点允许所有人访问,因此如果您尝试从stackoverflow.com更改为https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS ,它将起作用。

You can check whether an site allows cross access in network tab.您可以在网络选项卡中检查站点是否允许交叉访问。 See the below pic.见下图。 If its * all is allowed, or only the mentioned urls will be allowed.如果它的 * all 被允许,或者只允许提到的 urls 将被允许。

访问控制允许来源

Also note, angular by default considers all request to be json .另请注意,angular 默认将所有请求视为json If you are reading other types such as html , you need to specify that using {responseType: 'text'} as second argument.如果您正在阅读其他类型,例如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);
  });;

See Stackblitz live example参见Stackblitz 现场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM