42

DomSanitizer を使用してコンポーネント内の動的 URL をサニタイズしようとしていますが、このサービスのプロバイダーを指定する正しい方法がわかりません。

私は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 のプロバイダーを適切に提供する方法の例を教えてもらえますか? ありがとう!

4

4 に答える 4

75

providers: [ DomSanitizer ]もう宣言する必要はありません。以下に示すように
import DomSanitizer

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

コンポーネントでは、以下のようにコンストラクターを介して注入します。

constructor(private sanitizer: DomSanitizer) {}
于 2016-09-11T16:10:05.553 に答える
15

これらをインポートします-

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

変数を定義する-

trustedDashboardUrl : SafeUrl;

このようにコンストラクターで使用します-

constructor(
    private sanitizer: DomSanitizer) {}

次のように URL を指定します。

this.trustedDashboardUrl =
                        this.sanitizer.bypassSecurityTrustResourceUrl
                            ("URL");

これが役立つかどうかを確認してください。

于 2016-09-11T16:10:36.557 に答える
4

両方とも動作するはずです

constructor(private sanitizer: DomSanitizer) {}
constructor(private sanitizer: Sanitizer) {}

DomSanitizerこのタイプのみがキャストなしで必要なメソッドを提供するため、注入の方が優れています。

をインポートしたことを確認してくださいBrowserModule

@NgModule({
  imports: [BrowserModule],
})

RC.1 では、バインド構文を使用して一部のスタイルを追加できないも参照してください。

于 2016-09-11T16:10:01.257 に答える