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

查看:58
本文介绍了注意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()在第二部分中的更改. 我在组件A 中获取了params值,但在组件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属性的更改,您必须使用可观察对象. 如下更改服务.

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用于防止内存泄漏.

在您将名称设置为家庭服务"的任何地方,

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天全站免登陆