简体   繁体   中英

angular dependency injection - ignore when not provided - use case: MAT_DIALOG_DATA

some of my components. have 2 way initial parameters via constructor.

  1. routes parameters, for using via url.
  2. matDialogData, used when comopnent opens in a dialog.

like this:

constructor(private dialog: MatDialog,
private route:ActivatedRoute,
@Inject(MAT_DIALOG_DATA) private data)

the option of matDialog work fine, but route option (was work fine before adding of matDialogData) fail with:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[InjectionToken MatDialogData -> InjectionToken MatDialogData -> InjectionToken MatDialogData]: 
  NullInjectorError: No provider for InjectionToken MatDialogData!
NullInjectorError: R3InjectorError(AppModule)[InjectionToken MatDialogData -> InjectionToken MatDialogData -> InjectionToken MatDialogData]: 
  NullInjectorError: No provider for InjectionToken MatDialogData!

is there a way to config this parameter @Inject(MAT_DIALOG_DATA) private data as nullable/optional, and ignore from this error?

you can use the @Optional() decorator like this:

class SomeClass {
  constructor(
    private dialog: MatDialog,
    private route:ActivatedRoute,
    @Optional() @Inject(MAT_DIALOG_DATA) private data
  ) {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM