You didn’t really follow the rules. Other functions (notably saveItem) rely on this.itensSalvos being set. Directly or indirectly, the only place you can do that is inside the then() block where you are assigning it. You cannot assume that itensSalvos is set simply because you have called getSavedPosts(), which is what you are doing now.
In general, I don’t like having pages be so intimately involved with Storage. I would abstract much of this into a provider:
@Injectable() export class PostService {
savedPosts = new Subject<string>();
constructor(private _storage: Storage) {
_storage().ready()
.then(() => _storage.get('saved_posts'))
.then((sp) => this.savedPosts.next(sp));
}
setSavedPosts(sp: string): Promise<void> {
return this._storage.set('saved_posts', sp)
.then(() => this.savedPosts.next(sp));
}
addSavedPost(pid: string): Promise<void> {
let sp = this.savedPosts.value;
// tack pid onto sp
return this.setSavedPosts(sp);
}
removeSavedPost(pid: string): Promise<void> {
let sp = this.savedPosts.value;
// splice pid out of sp
return this.setSavedPosts(sp);
}
}
export class SavedPostsPage {
itensSalvos: string;
constructor(private _postsvc: PostService) {
_postsvc.savedPosts.subscribe(sp => this.itensSalvos = sp);
}
}
You can freely call this._postsvc.addSavedPost() and removeSavedPost() from your page, and the subscription made in the constructor will automatically ensure that itensSalvos stays up-to-date.
This could be improved by storing a Subscription and unsubscribing in one of the lifecycle events when your page is going away, but hopefully this will at least be sufficient to get you going.