我想弄清楚为什么在向构造函数添加属性时出现“无法解析所有参数...”错误。我似乎经常遇到这个错误,所以我认为我对这是如何工作有一个根本的误解。
请注意,我已阅读有关依赖注入的角度指南,但这似乎并未涵盖我的用例。我正在尝试做的具体事情是向我的组件添加动画,因此我按照本指南进行操作:https://angular.io/guide/animations。
以下代码有效:(从某种意义上说它不会爆炸)
import { Component, OnInit } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-new-payment',
templateUrl: './new-payment.component.html',
styleUrls: ['./new-payment.component.scss'],
animations: [
trigger('loadState', [
state('init', style({
marginRight: '-400px',
marginLeft: '400px'
})),
state('loaded', style({
marginRight: '0px',
marginLeft: '0px'
})),
transition('init => loaded', animate('100ms ease-in'))
])
]
})
export class NewPaymentComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
然而,我将构造函数更改为以下内容的那一刻:
constructor(public state = 'init') { }
我收到了错误。
现在我不完全理解为什么我要将它添加到构造函数中,而不是我试图模仿教程中的示例。在教程中有一个名为'state'的参数,它从'active'值变为'inactive',这是触发动画的内容。在我的代码中,我希望将state参数初始化为'init',然后我将在ngOnInit()函数中将其更改为'loaded'。这里的想法是每次加载组件时我的动画只会发生一次。
让我感到困惑的是,为什么这个变量'state'即使在构造函数参数中也是如此?从我读过的内容中可以看出,构造函数中的内容应该是依赖项,但这只是一个变量,所以我没有得到它。
(注意,使用Angular 5)
答案 0 :(得分:0)
When you create a component (directive, service, pipe) and use it without creating it's instance using new
- Angular automatically creates it's instance. Every parameter in the constructor of that component that Angular needs to resolve must be known to the Dependency Injection (DI) mechanism. DI tries to find that parameters in the providers, which are added into the NgModule or the component itself. DI mechanism tries to resolve the parameters based on
1) type
- public state: State
. DI tries to resolve the implementation of the type State
. You can pass under the State
type a primitive value, a class or something else. For more see Angular Providers.
2) InjectionToken
- @Inject(APP_CONFIG) config
. DI tries to find what is under the token APP_CONFIG
. For more see Angular Dependency injection tokens.
In your case DI mechanism does not know anything about the parameter state
and for that it throws to you an exception. You haven't provided enough information about that - type
or InjectionToken
.