1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Variable Change Detection - Angular

Discussão em 'Angular' iniciado por Brian Moreno, Outubro 9, 2024 às 14:02.

  1. Brian Moreno

    Brian Moreno Guest

    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.

    This is pretty much my code:

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

    }


    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! :)

    Continue reading...

Compartilhe esta Página