Created
January 14, 2019 12:53
-
-
Save sandy912/1739570d94f8b7eb94102f5eb085470c to your computer and use it in GitHub Desktop.
[Local Storage in Ionic] For storing and retriving the values loacally when no connection
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 { HttpClient } from '@angular/common/http'; | |
import { NetworkService, ConnectionStatus } from './network.service'; | |
import { Storage } from '@ionic/storage'; | |
import { Observable, from } from 'rxjs'; | |
import { tap, map } from "rxjs/operators"; | |
const API_STORAGE_KEY = 'specialkey'; | |
export class YoutubeService { | |
constructor(private http: HttpClient, | |
private networkService: NetworkService, | |
private storage: Storage) { } | |
getVideos(forceRefresh: boolean = false, playlistId): Observable<any[]> { | |
if (this.networkService.getCurrentNetworkStatus() == ConnectionStatus.Offline || !forceRefresh) { | |
return from(this.getLocalData(playlistId)); | |
} else { | |
return this.http.get('') | |
.pipe(map((res: Response) => res['items']), | |
tap(res => { | |
this.setLocalData(playlistId, res); | |
})); | |
} | |
} | |
private setLocalData(key, data) { | |
this.storage.set(`${API_STORAGE_KEY}-${key}`, data); | |
} | |
private getLocalData(key) { | |
return this.storage.get(`${API_STORAGE_KEY}-${key}`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment