typescript Angular2 EXCEPTION 没有 String 的提供者
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41882599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 EXCEPTION No provider for String
提问by Whisher
I've got a brand new app create with a ng-cli with this very simple code ^^
我用这个非常简单的代码用 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) {}
}
and I've got in the console
我进入了控制台
EXCEPTION: No provider for String!
例外:没有 String 的提供者!
I don't see any error in the code so what's wrong !
我在代码中没有看到任何错误,所以出了什么问题!
In ng-book I can read
在 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;
}
}
Take a look at
看一眼
https://github.com/Microsoft/TypeScriptSamples/blob/master/greeter/greeter.ts
https://github.com/Microsoft/TypeScriptSamples/blob/master/greeter/greeter.ts
回答by AJT82
Error in constructor:
构造函数中的错误:
export class AppComponent {
constructor(private my: string) {}
}
private my: string
should not be injected in the constructor, but outside, here assuming it's a variable you want to use in your component.
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!
}
}
I suggest you start of with the Tutorialfrom the beginning, so you learn the basics of Angular :)
我建议你从教程开始,这样你就可以学习 Angular 的基础知识:)
EDIT, the latter part you added is a class e.g for typing your object, not a component, for a typed Object of class Article, this is valid syntax:
编辑,您添加的后一部分是一个类,例如用于键入您的对象,而不是组件,对于类文章的类型化对象,这是有效的语法:
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;
}
}
Then you can import this class to your AppComponent
, and use to assign an Article
object.
然后您可以将此类导入到您的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() {}
}
回答by saber tabatabaee yazdi
I had this error and can solve it
我有这个错误并且可以解决它
just need to re-run the build process
只需要重新运行构建过程
by stopping it with cntrl+c
用 cntrl+c 停止它
and ionic serve
again
并ionic serve
再次
or angular command
或角度命令