0

I have a simple service to update an object. I deep clone the initial object and update the clone one.

As you can see, it works well, but the view is not updated. How can I do to update the view on changes ?

Here is the code : https://stackblitz.com/edit/angular-eh4cds?file=app%2Fapp.component.ts

And another question, how can I do to modify the value of number.three passing the path to function like : "number.three" ? : Answer here : https://stackoverflow.com/a/8817473/5627096

AppComponent

import { Component, OnInit } from '@angular/core';

import { ObjectService } from './object.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {

  private object: any;

  constructor (private objectService: ObjectService) {}

  ngOnInit () {
    this.object = this.objectService.getObject();
  }  

  changeObject () {
    this.objectService.changeObject('two', 'I\'m the one you need')
  }
}

ObjectService

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

@Injectable()
export class ObjectService {
    public object = {
      one: 'One',
      two: 'Two',
      number: {
        three: 'Three'
      }
    }

    public getObject () {
      return this.object;
    }

    public changeObject (path: string, value: any) {
      console.log('initial', this.object, path, value);
      let clone = { ...this.object, [path]: value };
      console.log('clone', clone);
      return this.object;
    }
}

View

{{ object.one }}
<br>
{{ object.two }}
<br>
{{ object.number.three }}
<br>

<button (click)="changeObject()">Change object</button>
Swarovski
  • 581
  • 2
  • 8
  • 25

1 Answers1

1

You need to assign the returned value inside the changeObject

  changeObject () {
    this.object =  this.objectService.changeObject('two', 'I\'m the one you need');

  }

Also i think you need to return cloned one instead of object

   public changeObject (path: string, value: any) {
      console.log('initial', this.object, path, value);
      let clone = { ...this.object, [path]: value };
      console.log('clone', clone);
      return clone;
    }

STACBKLITZ DEMO

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396