I have alert service in a angular 4 project. All components can set alerts in that service, but only some show them and each one shows them in a unique location. So my question is how is it possible to define get a variable from a service in all the html files?
My service looks like this:
import { Injectable } from '@angular/core';
@Injectable()
export class AlertService {
message;
constructor() { }
setMessage(message){
this.message = message;
}
}
And the component that wants to set a message just imports the service and calls setMessage method. But when i try to use message in html file like:
{{message}}
then its out of scope. How can i make this message accessible in all html files of all components?
Or maybe there is a better way to solve this kind of an requirement than a service variable?
In order to consume the message in your component you need to inject the service in your constructor (which you are probably doing).
Component:
export class MyComponent {
constructor(public alertService: AlertService)
In the markup reference alertService.message instead of message.
{{ alertService.message }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With