DomSanitizationService不是一个函数

Typ*_*nda 6 angularjs angular2-services angular

正如人们总是说没有一个被称为愚蠢问题的问题.

我现在正在学习Angular 2.0官方教程.正如我从packageconfig文件中看到的那样,它正在使用rc2.0.我试图压制框架工作抱怨iFrame标签中的"不安全"网址.

我已经检查了此Stack Overflow Question中的指令, 并按照LIVE Plunker中显示的所有内容进行操作.

我的VS代码在编译时没有抱怨任何内容,但是从Chrome检查器我可以看到错误.

在此输入图像描述

以下是我项目的TS文件.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute }       from '@angular/router';
import { ParcelsService } from './parcels.service';
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
import { Parcel } from './mock-parcels';
@Component({
  template: `
  <h2>Parcels</h2>
  <div *ngIf="parcel">
    <h3>"{{parcel.checkUrl}}"</h3>
    <iframe width=800 height=500 src="{{safeUrl}}}"></iframe>

    <p>
      <button (click)="gotoHeroes()">Back</button>
    </p>
  </div>
  `,
  providers:[ParcelsService, DomSanitizationService]
})
export class HeroDetailComponent implements OnInit, OnDestroy  {
  parcel: Parcel;
  safeUrl : SafeResourceUrl;
  private sub: any;
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: ParcelsService,
    private sanitizer: DomSanitizationService) {}
  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       let id = +params['id']; // (+) converts string 'id' to a number
       this.parcel = this.service.getParcel(id);
     });
     this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.parcel.checkUrl);

  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }
  gotoHeroes() { this.router.navigate(['/heroes']); }
}
Run Code Online (Sandbox Code Playgroud)

有没有人遇到类似的问题?请帮忙找出我做错了什么.

谢谢

rin*_*usu 9

您必须导入并提供BROWSER_SANITIZATION_PROVIDERS:

import { BROWSER_SANITIZATION_PROVIDERS, 
         SafeResourceUrl, 
         DomSanitizationService } from '@angular/platform-browser';
Run Code Online (Sandbox Code Playgroud)

在你的providers数组中:

providers: [ParcelsService, BROWSER_SANITIZATION_PROVIDERS]
Run Code Online (Sandbox Code Playgroud)

更新:对于最终版本,事情发生了一些变化

import { __platform_browser_private__, 
         SafeResourceUrl, 
         DomSanitizer } from '@angular/platform-browser';
Run Code Online (Sandbox Code Playgroud)

并将其添加到提供程序,如下所示:

providers: [ParcelsService, __platform_browser_private__, BROWSER_SANITIZATION_PROVIDERS]
Run Code Online (Sandbox Code Playgroud)

更新ANGULAR 4+:自Angular 4以来,有一些变化:

现在,你不必传递DomSanitizerproviders.您可以直接在组件中导入并在组件中抓取它constructor.同样如此SafeResourceUrl.

也:

  • __platform_browser_private__已经不在了@angular/platform-browser.
  • BROWSER_SANITIZATION_PROVIDERS已经不在了@angular/platform-browser.它现在被实现[作为提供者] BrowserModule可以从中导入@angular/platform-browser.
  • PS BrowserModule通常会添加到app.module 模块的导入数组中.