构建错误
常见错误
¥Common mistakes
忘记装饰器上的括号
¥Forgetting Parentheses on a Decorator
装饰器在注释后应有括号 ()
。一些例子包括:@Injectable()
、@Optional()
、@Input()
等
¥Decorators should have parentheses ()
after an annotation. Some examples include: @Injectable()
, @Optional()
, @Input()
, etc.
@Directive({
selector: 'my-dir',
})
class MyDirective {
// Wrong, should be @Optional()
// @Optional does nothing here, so MyDirective will error if parent is undefined
constructor(@Optional parent: ParentComponent) {}
}
常见错误
¥Common Errors
无法解析所有参数
¥Cannot Resolve all Parameters
Cannot resolve all parameters for 'YourClass'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'YourClass' is decorated with Injectable.
这一异常意味着 Angular 对 YourClass
构造函数的一个或多个参数感到困惑。为了执行 依赖注入,Angular 需要知道要注入的参数的类型。你可以通过指定参数的类来让 Angular 知道这一点。确保:
¥This exception means that Angular is confused about one or more of the parameters for YourClass
's constructor. In order to do dependency injection Angular needs to know the type of the parameter to inject. You let Angular know this by specifying the class of the parameter. Make sure:
-
你正在导入参数的类。
¥You are importing the parameter's class.
-
你已正确注释参数或指定其类型。
¥You have properly annotated the parameter or specified its type.
import { MyService } from 'my-service'; // Don't forget to import me!
@Component({
template: `Hello World`,
})
export class MyClass {
// service is of type MyService
constructor(service: MyService) {}
}
有时代码中的循环引用可能会导致此错误。循环引用意味着两个对象相互依赖,因此无法在彼此之前声明它们。为了解决这个问题,我们可以使用 Angular 内置的 forwardRef
函数。
¥Sometimes circular references within your code can cause this error. Circular references mean that two objects depend on each other, and so there is no way to declare both of them before each other. To get around this, we can use the forwardRef
function built in to Angular.
import { forwardRef } from '@angular/core';
@Component({
selector: 'my-button',
template: `<div>
<icon></icon>
<input type="button" />
</div>`,
directives: [forwardRef(() => MyIcon)], // MyIcon has not been defined yet
}) // forwardRef resolves as MyIcon when MyIcon is needed
class MyButton {
constructor() {}
}
@Directive({
selector: 'icon',
})
class MyIcon {
constructor(containerButton: MyButton) {} // MyButton has been defined
}
没有 ParamType 的提供者
¥No provider for ParamType
No provider for ParamType! (MyClass -> ParamType)
这意味着 Angular 知道它应该注入的参数类型,但它不知道如何注入它。
¥This means Angular knows the type of parameter it is supposed to inject, but it doesn't know how to inject it.