Skip to content

Is there a way to call .has(key) synchronously? #85

Answered by cyrilletuzi
alignsoft asked this question in Q&A
Discussion options

You must be logged in to vote

@alignsoft The basic answer is you need to chain your observables with switchMap().

It should look like this (after the declarations of your variables):

const getFromStorage$ = this.localStorage.getItem('test', { schema }).pipe(
  map((data) => decrypt(data)),
);

const getFromHttp$ = this.httpClient.get('test').pipe(
  takeUntil(this.ngUnsubscribe),
  delayWhen((data) => {
    const checkedData = !data.error ? data : {};
    const cryptedData = this.crypt ? this.encrypt(checkedData) : checkedData;
    return this.localStorage.setItem('test', cryptedData);
  }),
);

return this.localStorage.has(key).pipe(
  switchMap((hasKey) => (!navigator.onLine || hasKey) ? getFromStorage$ : getFromHttp$)

Replies: 5 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by cyrilletuzi
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #85 on December 08, 2020 21:28.