Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2/4 - best pratice of getting a variable from service in all html files of components?

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?

like image 559
user1985273 Avatar asked Jun 15 '17 21:06

user1985273


1 Answers

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 }}
like image 199
Joel Richman Avatar answered Oct 25 '22 23:10

Joel Richman