gpt4 book ai didi

javascript - @Inject 什么时候在 Angular 中是可选的?

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:31 24 4
gpt4 key购买 nike

我在 Angular 中有一个简单的服务

// service.ts
export class SimpleService {
// ...
}

// component.ts
@Component({
selector: 'my-component',
templateUrl: 'components/mycomp/mycomp.html',
providers: [
SimpleService
]
})
class MyComponent {
constructor(private ss: SimpleService) {}
}

上面的代码永远行不通。我收到一个错误:Uncaught Error: Can't resolve all parameters for MyComponent: (?).

但是,如果我将构造函数定义更改为:

class MyComponent {
constructor(@Inject(SimpleService) private ss: SimpleService) {}
}

然后就可以了。甚至文档似乎也没有使用 @Inject。从文档中我了解到,当我的提供者 token 不是类时,明确要求 @Inject;比如,尝试注入(inject)原始值,或使用不透明的标记等。

此外,我对 typescript 感到困惑。 Official documentation明确提到当 @Inject() 不存在时,Injector 将使用参数的类型注释。 如果类型信息在 typescript 转译过程中被删除,应用程序运行时发生 DI,那么 Angular 如何在运行时使用类型注释?有什么我想念的吗?

最佳答案

你忘了加

"emitDecoratorMetadata": true

到你的tsconfig.json

另见

关于javascript - @Inject 什么时候在 Angular 中是可选的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com