变量变化检测 - Angular [英] Variable Change Detection - Angular

查看:36
本文介绍了变量变化检测 - Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Angular 还是比较陌生,我主要使用 VueJS.我想知道如何检测变量何时更新.我正在通过 DataService 更新我的变量.我读过 ngOnChanges() 但我看到这仅适用于输入.

I'm fairly new to Angular, I work mainly with VueJS. I want to know how I can detect when a variable gets updated. I'm updating my variable through a DataService. I read about ngOnChanges() but I saw that this only works for inputs.

这几乎是我的代码:

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

我的服务

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

}

这是我更新变量的地方.

This is where I'm updating the variable.

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

非常感谢任何帮助!:)

Any help is greatly appreciated! :)

推荐答案

如果 myVar 只在 ngOnInit 定义的 Observable 回调中改变,你可以在之后调用一个方法改变变量:

If myVar is changed only in the Observable callback defined in ngOnInit, you can call a method after changing the variable:

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中调用方法:

On the other hand, if myVar can be changed in other places (since it is public), you can access it in a getter/setter, and call the method in the 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() {
        ...
    }
}

这篇关于变量变化检测 - Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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