Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch for changes in Angular 2 services function

I have a service named HomeService and in that service I am setting and getting some data which is working fine. Here is the code for my service.

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

@Injectable()
export class HomeService {

name:string;

constructor() { }

setParams(val) {
      this.name = val;
}
getParams() {
    return this.name;
}

}

I am setting params in a component A and getting it in component B. What I want is to keep watching the getParams() for changing in the second component. I am getting the params value in component A in which I am setting it but I couldn't get those value in Component B. Means in Component B its not watching for changes.

like image 874
Ahmer Khan Avatar asked May 19 '17 07:05

Ahmer Khan


People also ask

How to watch changes in $scope in AngularJS?

In angularjs $watch () function is used to watch the changes of variables in $scope object. Generally the $watch () function will create internally in angularjs to handle variable changes in application.

What is the use of $watch in AngularJS?

In angularjs $watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in angularjs to handle variable changes in application. Suppose in our angularjs applications if we want to create custom watch for some actions then it’s better to use $scope.watch function.

Why does angular update the HTML when aservice changes?

When an angular expression such as the one you used is present in the HTML, Angular automatically sets up a $watch for $scope.foo, and will update the HTML whenever $scope.foo changes. The unsaid issue here is that one of two things are affecting aService.foo such that the changes are undetected. These two possibilities are:

How to subscribe to form changes in angular?

The answer and demo are updated to align with latest Angular. You can subscribe to entire form changes due to the fact that FormGroup representing a form provides valueChanges property which is an Observerable instance: this.form.valueChanges.subscribe (data => console.log ('Form changes', data));


2 Answers

To track the changes of the name property you have to use observables. Change your service as below.

HomeService:

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

@Injectable()
export class HomeService {

    private nameSource = new Subject<any>();

    name$ = this.nameSource.asObservable();

    setParams(val) {
        this.nameSource.next(val);
    }

}

In your component B where you want the name to be changed, It always keep subscribed to the name in the service. So that whenever the name is changed in the service (When you set the name fro Component A), You can track the change and Component B will get updated.

ComponentB:

import { Component, OnInit, OnDestroy} from '@angular/core';
import 'rxjs/add/operator/takeWhile';
import { HomeService } from '[add path of home service here]';

export class ComponentBComponent implements OnInit, OnDestroy{

    private alive: boolean = true;
    private name: string;

    constructor(
        private homeService: HomeService;
    ) {
        homeService.name$.takeWhile(() => this.alive).subscribe(
            name=> {
                this.name = name;
        });

    }

    ngOnInit() {
        // Whatever to happen OnInit
    }

    ngOnDestroy() {
        this.alive = false;
    }

}

Please note that the takeWhile() and alive are used to prevent memory leaks.

From whatever the place you set the name to Home service,

this.homeService.setParams(name);

This solution should work for you.

like image 147
Saiyaff Farouk Avatar answered Oct 21 '22 07:10

Saiyaff Farouk


Consider re-logicate it with service based on subscribtion. In components you have to subscribe observable variable which is based on source, and whenever you call next method on source, the observable is firing and components that have subscribe this observable will receive new/updated value and inside subscribe callback you can define what would you do with that value. For more information check this article.

like image 28
Patryk Brejdak Avatar answered Oct 21 '22 07:10

Patryk Brejdak