使用 Angular 2 RC6 为组件提供 DomSanitizer 的正确方法 [英] Correct way Provide DomSanitizer to Component with Angular 2 RC6

查看:28
本文介绍了使用 Angular 2 RC6 为组件提供 DomSanitizer 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 DomSanitizer 清理组件内的动态 URL,但我似乎无法弄清楚为此服务指定提供者的正确方法是什么.

I'm attempting to use DomSanitizer to sanitize a dynamic URL within a Component using I can't seem to figure out what the correct way to specify a Provider for this service is.

我正在使用 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.

This results in the error this.sanitizer.bypassSecurityTrustResourceUrl is not a function at runtime.

有人可以向我展示如何正确提供 DomSanitizer 提供程序的示例吗?谢谢!

Could someone show me an example of how to properly provide a Provider for DomSanitizer? Thanks!

推荐答案

你不再需要声明 providers: [ DomSanitizer ].
只需要import DomSanitizer 如下图,

import { DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';

在组件中通过构造函数注入它,如下所示,

in component inject it through a constructor as below,

constructor(private sanitizer: DomSanitizer) {}

这篇关于使用 Angular 2 RC6 为组件提供 DomSanitizer 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆