Angular2 local storage Subject()

1.6k views Asked by At

I will explain you my (probably little) problem :)

I'm trying to make a localStorage which set and get some data (array of object). I have one component which add object in my local storage array and one other which get this data.

I'm on ionic2 tabs app, and when I set my local storage, my other view where I get this it's not update...

I think I have to use a RxJs Subject but I don't know how do this properly.

Have a look on my current code

// LocalStorageService.ts

export class LocalStorageService {
  public bookmarks: Subject<any> = new Subject()

  constructor (public alertCtrl: AlertController) {}


  setUserBookmarks(bookmarks: any) {
    localStorage.setItem("myData", JSON.stringify(bookmarks));
    this.bookmarks.next(bookmarks)
  }

  getUserBookmarks() {
    return JSON.parse(localStorage.getItem("myData"))
  }

Then, my components

// Component where I set data

export class ListEventsComponent {

 bookmarks: any

 constructor(private navParams: NavParams, 
 private localStorageService: LocalStorageService) {}

 ngOnInit() {
  this.localStorageService.bookmarks.subscribe(bookmarks => {
    this.bookmarks = bookmarks
  })
 }


 bookmark(event) {
  this.localStorageService.setUserBookmarks(event)
 }
}

and the last:

// Component where I get data

export class AboutPage {
 public bookmarks: any

 constructor(public navCtrl: NavController, private   localStorageService:LocalStorageService) {
   this.localStorageService.bookmarks.subscribe(bookmarks => {
     this.bookmarks = bookmarks
     console.log(bookmarks)
   })
 }

 removeBookmark(eventID: string) {
   this.localStorageService.removeUserBookmark(this.bookmarks, eventID)
 }
}

So, how can I update my second component when I set in the first ? Thank you in advance, if I'm not clear, don't hesitate to say it :)

1

There are 1 answers

1
Bazinga On BEST ANSWER

The problem is that your second component subscribe after the first is calling next, so he does not get any data. For this case you should use the BehaviorSubject to get the latest emitted value:

 public bookmarks: BehaviorSubject<any> = new BehaviorSubject([]); // The initial value