1

I have an object in a service, testProfile, which changes by many components. I want to call a method, saveToLocalStorage() from another service to save the changes of the testProfile object. How can I detect when the change happens in testProfile?

My code so far:

@Injectable()
export class ProfileService  {

  testProfile: ProfileInterface;
  private profileChangeWatcher = new Subject<ProfileInterface>(); 

  constructor(private localStorageService: LocalStorageService ) {

      this.testProfile = this.createProfile(this.localStorageService.loadProfile('testProfile'));
     
   }

   saveProfileChanges() {
      this.profileChangeWatcher.next(this.testProfile);
      this.localStorageService.saveToLocalStorage(this.testProfile);
  }
 
   createProfile(profileData: ProfileInterface): ProfileInterface {

    return new ProfileModel().init(profileData);
  }

}

3
  • after saveToLocalStorage function just use another Observable which will emit the latest data Jan 24, 2020 at 9:23
  • i added this to the code: this.profileChangeWatcher.subscribe((value)=> { this.localStorageService.saveToLocalStorage(this.testProfile); }) Where should i call the saveProfileChanges() method?
    – Davemester
    Jan 24, 2020 at 10:01
  • Can you provide me a Stackblitz demo? Jan 24, 2020 at 10:55

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.