I'm getting an error that says monetization has no inializer. I'm also getting an error inside ngOninit that says monetization is not assignable to type string | null.
export class MoviesPageComponent implements OnInit {
movies: MovieResults[] = [];
monetization: string;
constructor(private getMovies: GetMoviesService,
private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.paramMap.subscribe((params: ParamMap) => {
this.monetization = params.get('monetization');
});
CodePudding user response:
You get this error because monetization
is not initialized in the constructor.
What you'll need to do, is make the property optional.
export class MoviesPageComponent implements OnInit {
movies: MovieResults[] = [];
monetization?: string; // <-- add ? here
constructor(private getMovies: GetMoviesService,
private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.paramMap.subscribe((params: ParamMap) => {
this.monetization = params.get('monetization');
});
CodePudding user response:
If we look at the function specification of ParamMap.get...
get(name: string): string | null
the return type is string | null
, however type of monetization
property is
monetization: string;
and the assignment fails due to type inconsistency when we are doing
this.monetization = params.get('monetization'); //<-- Return type is string | null
To fix this,
- Make the property optional, as stated in the other answer. Like
monetization?: string
. Suffixing the property name with a?
implicits anundefined
in the type - Or, provide a default to satisfy null-ness of the value after reading from
ParamMap.get(...)
. Likethis.monetization = params.get('monetization') ?? '';
- If uncomfortable with making property optional, you can explicitly provide
string | undefined | null
to the type of the property. Likemonetization: string | null | undefined
.