繁体   English   中英

Angular2:提供模型服务-“没有模型提供者”

[英]Angular2: Service with Model - “no provider for model”

我正在尝试做的是创建一个使用模型来显示警报的服务。 除了该服务外,其他地方都没有必要使用警报模型,但是我无法进行这项工作。 我的服务:

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)

我是棱角新手,对此我不理解。 我想念什么? 提前致谢!

您需要在某处提供AlertModel

bootstrap(AppComponent, [AlertModel])

或在根组件中(首选):

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

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

@Inject(AlertModel)是多余的,如果构造器参数的类型已经是AlertModel @Inject()仅在类型不同或AlertModel没有@Injectable()装饰器时才需要。

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

您有此错误,因为没有从UserComponent组件(调用服务)可见的AlertModel类的提供程序。 引导应用程序时,可以在组件的providers属性中定义该类。

请参阅问题以了解有关分层注入器如何工作以及如何将事物注入服务的更多信息:

由于AlertModel类似乎是模型类,因此我认为您不需要注入它。 您可以简单地导入类并实例化它:

@Injectable()
export class AlertService {
  alertModel: AlertModel = new AlertModel();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM