变量检测 - 角度

时间:2018-04-21 22:29:25

标签: angular

我对Angular很新,我主要与VueJS合作。我想知道如何检测变量何时更新。我正在通过DataService更新我的变量。我读到了ngOnChanges(),但我看到这只适用于输入。

这几乎是我的代码:

import { DataService } from "../../service/my.service";

export class MainPage {
  myVar: String = ""; // this is the variable I want to listen when a change is made

   constructor (
    private data: DataService
   ) {}

   ngOnInit() {
    this.data.changeVar.subscribe(message => this.myVar = message);
  }
}

my.service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject<string>("");
  changeVar = this.messageSource.asObservable();

  constructor() { }

  changeMyVar (message: string) {
    this.messageSource.next(message)
  }

}

这是我正在更新变量的地方。

import { DataService } from "../../service/my.service";

export class AnotherPage {
  anotherVar: String = '';

  constructor(
    private data: DataService
  ) { }

  ngOnInit() {
    this.data.changeVar.subscribe(message => this.anotherVar = message)
  }

  myFunction () {
    this.data.changeMyVar("Hello"); // update variable to "Hello"
  }
}

非常感谢任何帮助! :)

2 个答案:

答案 0 :(得分:2)

如果myVar仅在ngOnInit中定义的Observable回调中更改,则可以在更改变量后调用方法:

export class MainPage {

    myVar: string = "";

    ngOnInit() {
        this.data.changeVar.subscribe(message => {
            if (message !== this.myVar) {
                this.myVar = message;
                this.doSomething();
            }
        });
    }

    private doSomething() {
        ...
    }
}

另一方面,如果myVar可以在其他地方更改(因为它是公共的),您可以在getter / setter中访问它,并在setter中调用该方法:

export class MainPage {

    private _myVar: string = "";

    get myVar(): string {
        return this._myVar;
    }
    set myVar(value: string) {
        if (value !== this._myVar) {
            this._myVar = value;
            this.doSomething();
        }
    }

    ngOnInit() {
        this.data.changeVar.subscribe(message => this.myVar = message);
    }

    private doSomething() {
        ...
    }
}

答案 1 :(得分:1)

您可以尝试使用此功能: https://angular.io/api/core/OnChanges

并使用以下命令获取对象更改: changes.objectName

angular.io页面上的更多详细信息。