Watch for changes in Angular 2 services function

巧了我就是萌 提交于 2020-01-13 10:48:05

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/44064535/watch-for-changes-in-angular-2-services-function

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