简体   繁体   中英

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

What I'm trying to do is create a service that uses a model to show an alert. The alert-model should be necessary nowhere else but in that service but I am not able to make this work. My service:

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';
        //...
    }
}

But I keep getting this error:

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

I'm new to angular and I do not understand this. What am I missing? Thanks in advance!

You need to provide the AlertModel somewhere

bootstrap(AppComponent, [AlertModel])

or in the root component (preferred):

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

Ensure AlertModel has the @Injectable() decorator and all its constructor parameters are provided as well (if it has any)

@Inject(AlertModel) is redundant if the type of the constructor parameter is already AlertModel . @Inject() is only necessary if the type differs or if AlertModel doesn't have the @Injectable() decorator.

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

You have this error since there is no provider for the AlertModel class visible from the UserComponent component (that calls the service). You can define either this class in the providers attribute of the component either when bootstrapping your application.

See the question to know more about how hierarchical injectors works and how to inject things into services:

Since the AlertModel class seems to be a model class I don't think that you need to inject it. You can simply import the class and instantiate it:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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