Reputation: 1410
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!
Upvotes: 0
Views: 1258
Reputation: 202276
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';
//...
}
}
Upvotes: 0
Reputation: 657781
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) {
Upvotes: 1