Created
February 23, 2020 22:27
-
-
Save datphan126/b155b4fd180f648de52bb256fe422f35 to your computer and use it in GitHub Desktop.
Book Offline Service for displaying data only
This file contains 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 Dexie from 'dexie'; | |
import { Book } from '../books/books.component'; | |
import { OnlineOfflineService } from './online-offline.service'; | |
import { BackendService } from '../services/backend.service'; | |
import { MatSnackBar } from '@angular/material/snack-bar'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class BookOfflineService { | |
private rDb: any; // this database is for caching data from the MongoDB | |
constructor( | |
private onlineOfflineService: OnlineOfflineService, | |
private backendService: BackendService, | |
private snackBar: MatSnackBar | |
) { | |
// Listen to network status events (i.e. online and offline) | |
this.registerToEvents(onlineOfflineService); | |
this.createDatabases(); | |
} | |
// Observe network status (i.e. online or offline) | |
private registerToEvents(onlineOfflineService: OnlineOfflineService) { | |
onlineOfflineService.connectionChanged.subscribe(online => { | |
if (online) { | |
this.snackBar.open("You are back online", 'Close', { duration: 2000 }); | |
} else { | |
this.snackBar.open("You are working offline", 'Close', { duration: 2000 }); | |
} | |
}); | |
} | |
private createDatabases() { | |
this.rDb = new Dexie('RBooks'); | |
this.rDb.version(1).stores({ | |
books: '_id,title,isbn,author,price,picture' | |
}); | |
} | |
public bulkAddToRDb(books: Array<Book>) { | |
return this.rDb.books | |
.bulkAdd(books) | |
.catch(e => { | |
alert('Error: ' + (e.stack || e)); | |
}); | |
} | |
public clearRDb() { | |
return this.rDb.books.clear(); | |
} | |
public async fecthAllItemsFromRDb() { | |
const books: Book[] = await this.rDb.books.toArray(); | |
return books; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment