Search code examples
angulartypescriptngoninit

unable to initialize class property inside ngOnit error


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');
    });

Solution

  • 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');
        });