The pipe 'safeResourceUrl' could not be fo

2020-04-15 15:32发布

问题:

Working on solving some security errors since I'm trying to dynamically embed youtube videos into my Angular 2 app. Found this answer here regarding the use of a Pipe to sanitize the url.

However running into this current error.

The pipe 'safeResourceUrl' could not be found

SafeResourceUrl.pipe.ts

import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeResourceUrl'})
export class SafeResourceUrl {
    constructor(private sanitizer:DomSanitizer){}

    transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}

I have it imported into my app.module

import { NgModule } from '@angular/core';
import { HomeModule } from './home/home.module';
import { SharedModule } from './shared/shared.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SafeResourceUrl } from './shared/pipes/saferesourceurl.pipe';

@NgModule({
    declarations: [
        AppComponent,
        SafeResourceUrl
    ],
    imports: [
        SharedModule,
        HomeModule,
        AppRoutingModule
    ]
})

And imported in my home.component.ts

import { SafeResourceUrl } from '../shared/pipes/saferesourceurl.pipe';

The markup for home.component.html

<div class="container col-lg-3 col-md-6 col-sm-12" *ngFor="let card of category.categorycards">
<div class="thumbnail">
    <a href="/wiki/entity" *ngIf="card.type == 'image'">
        <div class="image-wrap">
            <img [src]="card.graphic" class="img-responsive" alt="[card.title]" title="[card.title]">
        </div>
    </a>

    <a href="/wiki/category" *ngIf="card.type == 'video'">
        <div class="image-wrap">
            <iframe title="YouTube video player"
                    class="youtube-player" type="text/html" 

                    [src]="card.url | safeResourceUrl"

                    height="100%" width="100%" frameborder="0"></iframe>
        </div>
    </a>

回答1:

Pipes can't be made available globally. They need to be imported wherever they are used, the same as components or directives.

@NgModule({
    declarations: [
        SafeResourceUrl
    ],
    imports: [
      CommonModule
    ]
})
class SharedModule {
@NgModule({
    declarations: [
      CommonModule,
      HomeComponent,
    ],
    imports: [
        SharedModule,
    ]
})
class HomeModule