Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullInjectorError: No provider for String

After adding a string parameter to the constructor in my class I am getting an error in the browser:

enter image description here

My class is defined as follow:

import { Component, OnInit } from '@angular/core';

import { MatrixComponent } from '../matrix/matrix.component';

@Component({
  selector: 'app-player',
  templateUrl: './player.component.html',
  styleUrls: ['./player.component.css']
})
export class PlayerComponent implements OnInit {
    private userName: string;

    constructor(private name: string) {
        this.userName = name;
        this.discovered = 0;
        this.matrix = new MatrixComponent();
    }

    ngOnInit() {
    }
}

And I am creating the object in the constructor of another class:

var player1 = new PlayerComponent("Me");

I think it is possible to pass parameters in the constructor right? What's wrong with my code?

like image 200
Bonomi Avatar asked Jan 04 '18 23:01

Bonomi


1 Answers

As explained in this question,

the @Component decorator tells angular that it is a not a normal typescript class, but an Angular Component.

Thus, to make it work, you would have to tell it that string is a provider for your component, as it expects the constructor parameter to be a provider (which is either declared in the component's metadata or in the module).

string wouldn't work as it's not a known angular 2 provider (unless you create a service with name string).

This explains why we can create these kind of constructors (string as arguments) in normal classes but are not allowed in angular components.

I hope this helps :)

like image 170
planet_hunter Avatar answered Oct 02 '22 17:10

planet_hunter