关注 Angular 2 服务功能的变化

Watch for changes in Angular 2 services function

我有一个名为 HomeService 的服务,在该服务中我正在设置并获取一些工作正常的数据。这是我的服务代码。

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 中获取参数值,我正在其中设置它,但我无法在 Component B 中获取这些值。表示在 组件 B 中它不监视变化。

考虑使用基于订阅的服务对其进行重新逻辑化。在组件中,您必须订阅基于源的 observable 变量,并且每当您在源上调用 next 方法时,可观察对象就会触发,并且订阅此可观察对象的组件将收到 new/updated 值在 subscribe 回调中,您可以定义您将如何处理该值。有关详细信息,请查看此 article.

要跟踪名称的变化 属性,您必须使用可观察对象。 如下更改您的服务。

家庭服务:

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 将得到更新。

组件 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 用于 prevent memory leaks.

无论您在什么地方将名称设置为 Home 服务,

this.homeService.setParams(name);

此解决方案应该适合您。