无法在类内使用angulars localStorage,如何在会话之间进行缓存?

时间:2019-12-10 13:55:05

标签: angular caching

在第一个GET请求之后,我缓存了徽标,因此下次可以从缓存中返回徽标,而不必再次执行该请求。如果徽标已更新,我将删除缓存。

const BASE_URL = localStorage.getItem('resourceServer') + '/api/pictures/';

@Injectable()
export class PictureService {

  cachedLogo: Observable<Picture>;

  constructor(private http: HttpClient,
              private authService: AuthService,
              private notificationService: NotificationService,
              private handleService: HandleService) {
  }

  getLogo(): Observable<Picture> {
    if (!this.cachedLogo) {
      this.cachedLogo = this.http.get<Picture>(BASE_URL + 'logo', this.authService.setHeaders('application/json'))
        .pipe(
          publishReplay(1),
          refCount(),
          catchError(this.handleService.error.bind(this))
        );
    }
    return this.cachedLogo;
  }

  addPicture(picture: Picture): Observable<Picture> {
    this.cachedLogo = null;
    return this.http.post<Picture>(BASE_URL, picture, this.authService.setHeaders('application/json'))
      .pipe(
        tap(() => this.handleService.success('Bild hochgeladen')),
        catchError(this.handleService.error.bind(this))
      );
  }

  updatePicture(picture: Picture): Observable<Picture> {
    this.cachedLogo = null;
    return this.http.put<Picture>(BASE_URL + picture.id, picture, this.authService.setHeaders('application/json'))
      .pipe(
        tap(() => this.handleService.success('Bild bearbeitet')),
        catchError(this.handleService.error.bind(this))
      );
  }
}

当前的方法显然仅适用于会话。缓存不会在会话之间持续存在。但这就是我想要实现的目标。 localStorage在所有会话中都有效,但是我不能在课堂上使用它。那么如何在会话之间缓存该徽标?

1 个答案:

答案 0 :(得分:1)

您实际上从未将徽标保存在本地存储中。这就是为什么当您重新加载页面时总是要翻新它的原因。

可以从类内部毫无问题地访问LocalStorage服务。您可以添加一个setLogo函数,该函数会将徽标添加到本地存储中并设置属性this.cachedLogo。另外,您需要在加载类后恢复它。

在这里,我们正在实现onInit接口来添加ngOnInit函数,该函数将在类初始化时运行。在此功能中,我们从本地存储中检索徽标。

我们还添加了setLogo函数,该函数将设置变量cachedLogo并在localStorage中定义一个项。

const BASE_URL = localStorage.getItem('resourceServer') + '/api/pictures/';

@Injectable()
export class PictureService implements OnInit {

  cachedLogo: Observable<Picture>;

  constructor(private http: HttpClient,
              private authService: AuthService,
              private notificationService: NotificationService,
              private handleService: HandleService) {
  }

  getLogo(): Observable<Picture> {
    if (!this.cachedLogo) {
      this.setLogo(this.http.get<Picture>(BASE_URL + 'logo', this.authService.setHeaders('application/json'))
        .pipe(
          publishReplay(1),
          refCount(),
          catchError(this.handleService.error.bind(this))
        ));
    }
    return this.cachedLogo;
  }

  /* ... */
  setLogo(logo: string): void {
      LocalStorage.setItem('logo', logo);
      this.cachedLogo = logo;
  }

  ngOnInit() {
      this.cachedLogo = Localstorage.getItem('logo');
  }
}

PS 。请注意,此代码未经测试。