美好时光,
我正在尝试使用 Angular2 制作一个应用程序。
路由:
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'first/:id', component: FirstComponent}
];
也就是说,当转到 site/first/... 时,控制传递给 FirstComponent 组件,它可以检索 id 参数。当请求 site/first/item 时,id 参数将等于“item”等。
根据此参数,使用该服务的组件向服务器发送请求以接收数据。根据id参数生成请求地址。也就是说,在这种情况下,请求将在 item.html 上。数据是一段 html 代码,将被插入到模板中的特定位置。
问题:如何以html的形式获取这些数据。到目前为止,只接收到字符串,并将其与标签一起直接插入到页面中。
请求所需文件的服务:
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.httpService.getData('data.html').subscribe((data: Response) => this.code=data.text());
我知道问题出在所使用的 text() 方法中,因为它返回了一个字符串。如果请求的文件中的数据是简单的 html 标记形式,我如何才能正确获取 html 形式的数据?
我是否需要使用 Response 类的其他方法(我不知道)或以某种方式处理接收到的字符串(如何?)或使用 json(也就是说,源数据需要以某种方式转换为这种格式?)
请告诉我 :) 感谢您的回答!
出于安全原因,当通过 {{}} 插值插入变量或默认设置 innerHTML 时,HTML 将被转义。
详情在这里:https ://angular.io/docs/ts/latest/guide/security.html
因此,为了解决这个问题,您需要标记您信任此代码,但这是一个潜在的漏洞。