Watch for changes in Angular 2 services function

Deadly 提交于 2019-12-05 09:28:38

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!