NullInjectorError:没有字符串提供程序

Bon*_*omi 3 typescript angular

将字符串参数添加到类中的构造函数后,浏览器出现错误:

在此处输入图片说明

我的课程定义如下:

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() {
    }
}
Run Code Online (Sandbox Code Playgroud)

我在另一个类的构造函数中创建对象:

var player1 = new PlayerComponent("Me");
Run Code Online (Sandbox Code Playgroud)

我认为可以在构造函数中传递参数吗?我的代码有什么问题?

pla*_*ter 5

正如这个问题所解释的,

@Component装饰告知angular,这是一个不正常的typescript class,但是一个Angular Component

因此,要使其正常工作,您必须告诉它stringprovider您组件的“ a”,因为它希望构造函数参数是提供程序(在组件的medata或模块中声明)。

string无法使用,因为它不是已知的angular 2提供程序(除非您使用name创建服务string)。

这解释了为什么我们可以string在普通类中创建此类构造函数(作为参数),但在角度组件中不允许这样做。

我希望这有帮助 :)