1

I cant seem to figure out the best solution for this say I have a api call that gets me an object of facts like so..

facts: {
    name: 'james',
    age: 23,
    address: '123 fake st'
}

and I want to be able to use this all over my app, but I also want to be able to update single properties so like if I press a button I want to be able to update the name on that object

so like I could do something like this

storeFact() {
   this.service.facts.name = 'nick'
}

and then the object would update in the service and look like this..

facts: {
   name: 'nick',
   age: 23,
   address: '123 fake st'
}

and then obviously I could then call that in my app again like {{facts.name}} and that would return nick

but not only that I want to be able to add new keys and values as well so I could have a button that does this..

newFact() {
   this.service.facts.hobbies = 'swimming';
}

Im not entirely sure how this could work, If I call the api and store the returned result which is the facts object in a shared service can I add, grab and change key value pairs??

and If I used the classic BehaviorSubject and observable route on the .next() wouldnt that destroy the current object when I pass in the this.service.facts.name = 'nick'

any help would be appreciated

Thanks

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
  • Possible duplicate of [Persist class property Angular 5](https://stackoverflow.com/questions/50553209/persist-class-property-angular-5) – Vikas May 31 '18 at 04:01

1 Answers1

1

Its not the most elegant solution and this was for an earlier version of angular but should still work. You can use local storage to store a variable and access it across your app. In your case

    this.facts = JSON.parse(localStorage.getItem('facts'));
    this.facts.hobbies = 'swimming';
    localStorage.setItem('facts', JSON.stringify(this.facts));
Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33