我正在尝试使用 DomSanitizer 来清理组件中的动态 URL,但我似乎无法弄清楚为该服务指定 Provider 的正确方法是什么。
我正在使用 Angular 2.0.0-rc.6
这是我当前的组件:
@Component({
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [ DomSanitizer ],
})
export class AppComponent implements OnInit
{
public url: SafeResourceUrl;
constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {
let id = 'an-id-goes-here';
let url = `https://www.youtube.com/embed/${id}`;
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
ngOnDestroy() {}
}
这会导致运行时出现错误 this.sanitizer.bypassSecurityTrustResourceUrl is not a function
。
有人可以向我展示如何为 DomSanitizer 正确提供 Provider 的示例吗?谢谢!
原文由 kalmas 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不再需要声明
providers: [ DomSanitizer ]
。只需要
import
DomSanitizer
如下图,在组件中通过构造函数注入它,如下所示,