/questions/41882599/angular2-exception-no-provider-for-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.
@Whisher To cut things short and MUCH simplified, the@Component
decorator tells that AppComponent is a not a "normal" class, but a Component. And in that case you would have to tell thatstring
is a provider for your component, because it expects that what is in injected in the constructor should be a provider, and therefore declared inproviders: [string]
in your component or ngModule. "string" wouldn't work as it's no known angular 2 provider, unless you create a service (or whatever) that is namedstring
and has Angular magic in it ;) As said this was just a simplified example.
虽然我还没理解到底为什么,也没找到具体的解释的地方,不过@component 主键中的construct 里确实不能带属性构造函数参数,会报错
实际上我在开发的时候打开 F12 有时候是看不到的,不同的浏览器看到的信息不同,下面的是ie edge 的返回的错误,才让我找到了上面的 回答。 有时候换一换思路是对的。
HTML1300: 进行了导航。
localhost:4200
当前窗口: localhost
ERROR Error: StaticInjectorError(AppModule)[HelloStep1Component -> String]:
StaticInjectorError(Platform: core)[HelloStep1Component -> String]:
NullInjectorError: No provider for String!
Function code (10) (5,3)
"ERROR"
{
[functions]: ,
__proto__: { },
description: "NullInjectorError: No provider for String!",
message: "StaticInjectorError(AppModule)[HelloStep1Component -> String]:
StaticInjectorError(Platform: core)[HelloStep1Component -> String]:
NullInjectorError: No provider for String!",
name: "Error",
ngDebugContext: { },
ngTempTokenPath: null,
ngTokenPath: [ ],
stack: "Error: StaticInjectorError(AppModule)[HelloStep1Component -> String]:
StaticInjectorError(Platform: core)[HelloStep1Component -> String]:
NullInjectorError: No provider for String!
at NullInjector.prototype.get (http://localhost:4200/vendor.js:30329:13)
at resolveToken (http://localhost:4200/vendor.js:30566:9)
at tryResolveToken (http://localhost:4200/vendor.js:30511:9)
at StaticInjector.prototype.get (http://localhost:4200/vendor.js:30408:13)
at resolveToken (http://localhost:4200/vendor.js:30566:9)
at tryResolveToken (http://localhost:4200/vendor.js:30511:9)
at StaticInjector.prototype.get (http://localhost:4200/vendor.js:30408:13)
at resolveNgModuleDep (http://localhost:4200/vendor.js:37456:9)
at NgModuleRef_.prototype.get (http://localhost:4200/vendor.js:38144:9)
at resolveDep (http://localhost:4200/vendor.js:38509:5)"
}