Created
February 21, 2020 13:21
-
-
Save adsonrocha/79c67fb5f89da9e86b37596682822322 to your computer and use it in GitHub Desktop.
ionic-offline-example-post-service-create
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from '@angular/core'; | |
import {Storage} from '@ionic/storage'; | |
import {of, Subject} from 'rxjs'; | |
import {Post} from '../model/Post'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class PostsService { | |
postsSubject: Subject<Post[]> = new Subject<Post[]>(); | |
posts: Post[] = []; | |
constructor( | |
private storage: Storage, | |
) { | |
} | |
async create(data: Post): Promise<void> { | |
let result: Promise<any>; | |
const online: boolean = navigator.onLine; | |
// IF CALLED BY doItLater, DATA ALREADY HAS AN ID | |
data.id = data.id ? data.id : Math.floor(1000 * Math.random()); | |
if (!online) { | |
result = this.doItLater('create', data); | |
} else { | |
// HERE YOU WOULD UPDATE YOUR DATABASE | |
result = of(this.posts.push(data)).toPromise(); | |
} | |
if (!this.posts.some(el => el.id === data.id)) { | |
this.posts.push(data); | |
} | |
await this.storage.set(`cache:post:${data.id}`, data); | |
return result.then(async _ => { | |
this.postsSubject.next(this.posts); | |
}); | |
} | |
doItLater(operation, data): Promise<any> { | |
switch (operation) { | |
case 'create': | |
return this.storage.set(`offline:post:${operation}:${data.id}`, data); | |
break; | |
case 'update': | |
return this.storage.set(`offline:post:${operation}:${data.id}`, data); | |
break; | |
case 'remove': | |
return this.storage.set(`offline:post:${operation}:${data.id}`, data); | |
break; | |
default: | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment