Jydon Mah
Jydon Mah

Reputation: 383

Angular 2: how to detect changes of property in services?

Im using service to centralize my logic code, however i can't find a way on how to inform my other component when my property _opened in my service is being change..

app.service.ts

import { Injectable} from '@angular/core'; 

export class AsideService{
  _opened: boolean = true;

  _toggleSidebar() {
    this._opened = !this._opened;
     return this._opened;
  }
}

dashboard.component.html

<p (click)="_toggleSidebar()">
   <span></span>
   <span></span>
   <span></span>

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { AsideService } from '../aside.service';  

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    open: any;

  constructor(private asideService: AsideService) {
    this.open = this.asideService._toggleSidebar();
  }

  ngOnInit() {
  }
}

Upvotes: 2

Views: 638

Answers (1)

uksz
uksz

Reputation: 18699

There are couple of ways that you can do that. The most obvious reason would be to pass object containing _opened variable to the component. You would then have something like the following:

import { Injectable} from '@angular/core'; 

export class AsideService{
  _state: Object = {
     _opened: true
  };

  _toggleSidebar() {
    this._state._opened = !this._state._opened;
     return this._state;
  }

  _getState(){
    return this._state;
  }
}

and in your component, you would need to check for the value of _state._opened from service. This is because you can't pass the primitive values between the components - you need to surround them in an object. Then, for example in you component, you can go:

export class DashboardComponent implements OnInit { serviceState: any; constructor(private asideService: AsideService) { this.serviceState = this.asideService._toggleSidebar(); } }

and in your components HTML:

<div>{{serviceState._opened}}</div>

Which will show you the value of _opened in your service.

The other way would involve events, but I wouldn't recommend this.

Upvotes: 1

Related Questions