Angular2管道内DomSanitizer未定义问题求助
Hey there, it looks like you're hitting a snag where DomSanitizer is coming up undefined in your custom Angular pipe. Let's break down the most likely causes and how to fix them:
1. Make Sure You've Imported the Required Module in Your Root Module
DomSanitizer is part of Angular's @angular/platform-browser package, and Angular only provides its instance if you've imported BrowserModule (for browser environments) or BrowserAnimationsModule (if you're using animations) in your root module (usually AppModule). Here's how your module should look:
// app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { YoutubePipe } from './path-to-your-pipe/youtube.pipe'; // Update this path to match your pipe's location @NgModule({ declarations: [ YoutubePipe, // Your other components, directives, and pipes go here ], imports: [ BrowserModule, // This is critical for getting DomSanitizer working // Any other modules you're using (like HttpClientModule, etc.) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2. Double-Check Your Pipe's Import and Injection Syntax
It looks like your current injection code is mostly right, but let's verify you haven't made a typo or missed an import:
// youtube.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; // Confirm this line exists and is spelled correctly @Pipe({ name: 'youtube', }) export class YoutubePipe implements PipeTransform { // Make sure the type here is exactly DomSanitizer (case-sensitive!) constructor(private sanitizer: DomSanitizer){} transform(value: string): any { // Add a guard clause to avoid errors if the input is null/undefined if (!value) return null; const embedUrl = value.replace('watch?v=', 'embed/'); console.log(embedUrl); return this.sanitizer.bypassSecurityTrustResourceUrl(embedUrl); } }
3. Check for Angular Version Compatibility
If you're working with an older Angular version (pre-Angular 5), DomSanitizer used to be called DomSanitizationService. If that's the case, update your import and injection:
import { DomSanitizationService } from '@angular/platform-browser'; // In your constructor: constructor(private sanitizer: DomSanitizationService){}
4. Ensure Your Pipe is Properly Declared
Double-check that your YoutubePipe is added to the declarations array of the module where it's used (usually the root AppModule). If it's declared in a feature module, make sure that module is imported into your root module.
One last tip: Sometimes Angular's dev server can hold onto old cache, so try restarting ng serve after making these changes—it might resolve weird dependency injection glitches.
内容的提问来源于stack exchange,提问作者Rob

