Angular2 EXCEPTION没有String的提供者

Whi*_*her 9 typescript ionic3 angular

我有一个全新的应用程序使用ng-cli创建这个非常简单的代码^^

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private my: string) {}
} 
Run Code Online (Sandbox Code Playgroud)

而且我已进入控制台了

EXCEPTION:没有String的提供者!

我没有在代码中看到任何错误,所以有什么不对!

在ng-book中,我可以阅读

export class Article { 
  title: string; 
  link: string; 
  votes: number;
  constructor(title: string, link: string, votes?: number) { 
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

看一眼

https://github.com/Microsoft/TypeScriptSamples/blob/master/greeter/greeter.ts

AJT*_*T82 16

构造函数中的错误:

export class AppComponent {
  constructor(private my: string) {}
} 
Run Code Online (Sandbox Code Playgroud)

private my: string 不应该在构造函数中注入,而是在外部,这里假设它是您要在组件中使用的变量.

export class AppComponent {
  private my: string;
  constructor() {
    this.my = 'Hello!'; // if you want to assign a value (in the constructor) to your string, do it here!
  }
} 
Run Code Online (Sandbox Code Playgroud)

我建议你从一开始就开始使用Tutorial,这样你就可以学习Angular的基础知识:)

编辑,你添加的后一部分是一个类,例如用于键入你的对象而不是组件,用于类别文章的类型化对象,这是有效的语法:

export class Article { 
  title: string; 
  link: string; 
  votes: number;
  constructor(title: string, link: string, votes?: number) { 
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将此类导入到您的AppComponent,并用于分配Article对象.

import { Component } from '@angular/core';
import { Article } from './your.path'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  article: Article = new Article('titleHere', 'linkHere', 3)

  constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

  • @Whisher为了简化和简化,`@ Component`装饰器告诉AppComponent不是一个"普通"类,而是一个Component.在这种情况下,您必须告诉`string`是您的组件的提供者,因为它期望构造函数中注入的内容应该是提供者,因此在组件中的`providers:[string]`中声明或ngModule."string"不起作用,因为它不是已知的角度2提供者,除非你创建一个名为`string`的服务(或其他)并且在其中具有Angular魔法;)如上所述,这只是一个简化的例子. (2认同)