Home > Software engineering >  unable to initialize class property inside ngOnit error
unable to initialize class property inside ngOnit error

Time:03-15

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,

  1. Make the property optional, as stated in the other answer. Like monetization?: string. Suffixing the property name with a ? implicits an undefined in the type
  2. Or, provide a default to satisfy null-ness of the value after reading from ParamMap.get(...). Like this.monetization = params.get('monetization') ?? '';
  3. If uncomfortable with making property optional, you can explicitly provide string | undefined | null to the type of the property. Like monetization: string | null | undefined.
  • Related