簡體   English   中英

注意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中設置params並將其放入組件B中 我想要的是繼續觀察getParams()以便在第二個組件中進行更改。 我在組件A中得到params值,我在其中設置它,但我無法在組件B中獲得這些值。 組件B中的意思是不注意變化。

要跟蹤name屬性的更改,您必須使用observables。 如下更改您的服務。

主頁服務:

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將更新。

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

}

請注意, takeWhile()alive用於防止內存泄漏。

從您設置名稱到家庭服務的任何地方,

this.homeService.setParams(name);

此解決方案應該適合您。

考慮使用基於訂閱的服務對其進行重新邏輯化。 在組件中,您必須訂閱基於源的observable變量,並且每當您在源上調用next方法時,observable都會觸發,訂閱此observable的組件將接收新的/更新的值,並且在subscribe回調中您可以定義什么做那個價值。 有關更多信息,請查看此文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM