构建错误
常见问题
装饰器缺少圆括号
装饰器在注解后应该带有圆括号 ()。常见示例包括:@Injectable()、@Optional()、@Input() 等。
@Directive({
selector: 'my-dir',
})
class MyDirective {
// 错误,应为 @Optional()
// 此处的 @Optional 无效,若 parent 未定义将导致 MyDirective 报错
constructor(@Optional parent: ParentComponent) {}
}
常见错误
无法解析所有参数
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。请确保:
- 已导入参数的类
- 已正确注解参数或指定其类型
import { MyService } from 'my-service'; // 别忘了导入!
@Component({
template: `Hello World`,
})
export class MyClass {
// service 的类型为 MyService
constructor(service: MyService) {}
}
有时代码中的循环引用会导致此错误。循环引用意味着两个对象相互依赖,因此无法在彼此之前声明两者。要解决此问题,可以使用 Angular 内置的 forwardRef 函数。
import { forwardRef } from '@angular/core';
@Component({
selector: 'my-button',
template: `<div>
<icon></icon>
<input type="button" />
</div>`,
directives: [forwardRef(() => MyIcon)], // MyIcon 尚未定义
}) // 当需要 MyIcon 时,forwardRef 会解析为 MyIcon
class MyButton {
constructor() {}
}
@Directive({
selector: 'icon',
})
class MyIcon {
constructor(containerButton: MyButton) {} // MyButton 已定义
}
缺少 ParamType 的提供者
No provider for ParamType! (MyClass -> ParamType)
这意味着 Angular 知道要注入的参数类型,但不知道如何注入它。