gpt4 book ai didi

javascript - Angular 2 : Service with Model - "no provider for model"

转载 作者:行者123 更新时间:2023-12-03 06:53:38 24 4
gpt4 key购买 nike

我想做的是创建一个使用模型来显示警报的服务。除了该服务之外,警报模型在其他任何地方都应该是必要的,但我无法使这项工作发挥作用。我的服务:

import {Injectable, Inject} from "angular2/core";
import {AlertModel} from "../models/alert.model";

@Injectable()
export class AlertService {
constructor(@Inject(AlertModel) alertModel: AlertModel) {
}

public alert(){
this.alertModel.message = 'success';
//...
}
}

但我不断收到此错误:

Uncaught (in promise): No provider for AlertModel! (UserComponent -> AlertService -> AlertModel)

我是 Angular 新手,我不明白这一点。我缺少什么?提前致谢!

最佳答案

您需要在某处提供AlertModel

bootstrap(AppComponent, [AlertModel])

或者在根组件中(首选):

@Component({
selector: 'my-app',
providers: [AlertModel],
...
})

确保 AlertModel 具有 @Injectable() 装饰器,并且还提供了其所有构造函数参数(如果有)

如果构造函数参数的类型已经是 AlertModel,则

@Inject(AlertModel) 是多余的。仅当类型不同或 AlertModel 没有 @Injectable() 装饰器时才需要 @Inject()

constructor(@Inject(AlertModel) alertModel: AlertModel) {

关于javascript - Angular 2 : Service with Model - "no provider for model",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37386178/

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