Munna Babu
Munna Babu

Reputation: 5756

How to find Object value change detection inside Angular 4 service?

I using service and it has some objects and i want to find detection when the object changes. I tried below methods but didn't work. Please someone help me how to find detection of the variable or object inside Service.

Could someone please help me how to find object/variable change ? (Not by using formcontrol valueChanges)

when ever the myObject get change inside the service , i want to call method. I am not sure how to find detection of variable or object in angular. Could someone please help me on it.

 export MyShareService () {
     public myObject: any;

      //  when ever the myObject value initialized(change) on mytestcomponent , i need to call below function changeDetactedOnMyObject()

     public changeDetactedOnMyObject(){
         console.log('detacted');
     }
  }


export MyTestComponent() {
   constructor(private myShare: MyShareService){

   }
    ...
    ...
   ngOninit(){
      this.myShare.myObject = this.componentValue;
   }
}

Upvotes: 0

Views: 834

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657308

There is no change detection of objects. Angular only does change detection of view bindings. What you can do

export MyShareService () {
   private myObject$: Subject<any> = new Subject<any>();
   public myObject: this.myObject$.asObservable();

   public updateMyObject(newValue) {
     this.myObject$.next(newValue);
   }

   constructor() {
        this.myObject.subscribe(
            (data) => { console.log('change detacted'); },
            (error) => {  console.log(error) }
        )
    }
}

Upvotes: 1

Related Questions