Good time,

I'm trying to make an application using Angular2.

Routing:

const appRoutes: Routes = [ {path: '', component: HomeComponent}, {path: 'first/:id', component: FirstComponent} ]; 

That is, when navigating to the site / first / ... address, control passes to the FirstComponent component and it can extract the id parameter. When prompted for site / first / item, the id parameter will be equal to "item" and so on.

Depending on this parameter, the component uses the service to send a request to the server to receive data. Based on the id parameter, the request address is generated. That is, in this case, the request will be for item.html. Data is a piece of html-code that will be inserted at a specific place in the template.

Question: how do I get this data in the form of html. So far, only a string is obtained, and it is inserted directly on the page along with the tags.

Service requesting the desired file:

 import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; @Injectable() export class HttpService{ constructor(private http: Http){ } getData(address: string){ return this.http.get(address); } } 

This is how I get the data in the component:

 this.httpService.getData('data.html').subscribe((data: Response) => this.code=data.text()); 

I understand that the matter is in the used text () method, because it returns a string. How do I get the data correctly in the form of html, if in the requested file they are in the form of a simple html markup?

Do I need to use some other method of the Response class (which I don’t know about) or somehow process the resulting string (how?) Or use json (that is, do I need to somehow bring the source data to this format?)

Tell me please :) Thanks for the answers!

  • how does it fit into the page? - Grundy

1 answer 1

When you insert a variable through interpolation {{}} or by assigning innerHTML by default, HTML will be escaped, for security reasons.

Details here: https://angular.io/docs/ts/latest/guide/security.html

Interpolated content is always escaped — it’s not interpreted.

For the HTML to be interpreted, you must bind it to an HTML property such as innerHTML. But there is no need for XSS vulnerability.

Accordingly, to get around this, you must mark that you trust this code, but this is a potential hole.

 constructor(private sanitizer: DomSanitizer) {} ... this.httpService.getData('data.html').subscribe((data: Response) => this.code=sanitizer.bypassSecurityTrustHtml(data.text())); 
  • On the page where you sent me, I found this beauty: <p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p> html-formatting is saved, and the scripts are ignored) Thank you very much ! The whole head broke)) - Furry Cat