观察 Angular 2 服务功能的变化 [英] Watch for changes in Angular 2 services function

查看:19
本文介绍了观察 Angular 2 服务功能的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 HomeService 的服务,在该服务中,我正在设置并获取一些运行良好的数据.这是我的服务的代码.

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;
}

}

我正在组件A中设置参数并在组件B中获取它.我想要的是继续观察 getParams() 在第二个组件中的变化.我在 component A 中获得了 params 值,我在其中设置了它,但我无法在 component B 中获得这些值.意味着在组件 B 中它不关注变化.

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.

推荐答案

要跟踪 name 属性的更改,您必须使用 observables.如下更改您的服务.

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

家庭服务:

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);
    }

}

在您希望更改名称的组件 B 中,它始终保持订阅服务中的名称.这样无论何时在服务中更改名称(当您为组件 A 设置名称时),您都可以跟踪更改并且组件 B 将得到更新.

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.

组件B:

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;
    }

}

请注意,takeWhile()alive 用于 防止内存泄漏.

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

无论您将名称设置为 Home service 的任何位置,

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

this.homeService.setParams(name);

这个解决方案应该适合你.

This solution should work for you.

这篇关于观察 Angular 2 服务功能的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆