Skip to content

Instantly share code, notes, and snippets.

@vcpablo
Created March 3, 2019 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vcpablo/57b8133bae072e1d9fb179ac341c613a to your computer and use it in GitHub Desktop.
Save vcpablo/57b8133bae072e1d9fb179ac341c613a to your computer and use it in GitHub Desktop.
Ionic + Akita state management issue
// Required imports
export class ContactsTab1Page implements OnInit {
contacts$: Observable<Contact[]>;
}
// Constructor
// Executed each time the tab is activated
ionViewWillEnter(){
this.contactsService.get().subscribe();
this.contacts$ = this.contactsQuery.selectAll();
}
toggleStarred(contact: Contact) {
let data = Object.assign({}, contact);
data.starred = !data.starred;
this.contactsService.updateContact(data);
}
// Required imports
export class ContactsTab2Page implements OnInit {
contacts$: Observable<Contact[]>;
}
// Constructor
// Executed each time the tab is activated
ionViewWillEnter(){
this.contactsService.get().subscribe();
this.contacts$ = this.contactsQuery.selectAll();
}
toggleStarred(contact: Contact) {
let data = Object.assign({}, contact);
data.starred = !data.starred;
this.contactsService.updateContact(data);
}
import { QueryEntity, ID } from '@datorama/akita';
import { Injectable } from '@angular/core';
import { ContactsStore, State } from './contacts.store';
import { Contact } from './contact.model';
@Injectable()
export class ContactsQuery extends QueryEntity<State, Contact> {
constructor(protected store: ContactsStore) {
super(store);
}
}
// Required imports
// Returns all contacts
get() {
const request = this.contactsDataService.getContacts().pipe(
tap(contacts => this.contactsStore.set(contacts))
);
return this.contactsStore.isPristine ? request : noop();
}
// Updates a contact
updateContact(contact: Contact) {
this.contactsStore.createOrReplace(contact.id, { ...contact })
}
import { Contact } from './contact.model';
import { EntityState, EntityStore, StoreConfig } from '@datorama/akita';
import { Injectable } from '@angular/core';
export interface State extends EntityState<Contact> {}
@Injectable()
@StoreConfig({ name: 'contacts', resettable: true })
export class ContactsStore extends EntityStore<State, Contact> {
constructor() {
super();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment