我用 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) {}
}
我已经进入了控制台
异常:没有字符串的提供者!
我没有看到代码中有任何错误,所以 怎么了!
在 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;
}
}
看看
https://github.com/Microsoft/TypeScriptSamples/blob/master/greeter/greeter.ts
最佳答案
构造函数错误:
export class AppComponent {
constructor(private my: string) {}
}
private my: string
不应注入(inject)到构造函数中,而是注入(inject)到外部,这里假设它是您要在组件中使用的变量。
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!
}
}
我建议您从 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;
}
}
然后您可以将此类导入您的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() {}
}
关于Angular2 异常没有字符串提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41882599/