Restoring cached data
At the beginning of the chapter, when implementing the updateUser
method in UserService
, we cached the user
object in case of any errors that may wipe out user-provided data:
src/app/user/user/user.service.ts
updateUser(id: string, user: IUser): Observable<IUser> {
...
this.setItem('draft-user', user)
...
}
Consider a scenario where the user may be temporarily offline when they attempt to save their data. In this case, our updateUser
function will save the data.
Let's see how we can restore this data in ProfileComponent
when loading the user profile:
- Start by adding functions named
loadFromCache
andclearCache
to theProfileComponent
class:src/app/user/profile.component.ts private loadFromCache(): Observable<User | null> { let user = null try { const draftUser = localStorage.getItem('draft-user') if (draftUser != null) { user = User.Build(JSON.parse(draftUser))...