사용자 방문 기억을 위한 로컬 저장소 사용
로컬 스토리지란 무엇입니까?
로컬 저장소는 사용자 행동에 따라 데이터를 저장할 수 있는 DOM의 개체입니다.
localStorage
개체에 데이터를 저장하면(sessionStorage
와 달리) 개체는 만료되지 않습니다. 이는 set
메서드를 사용하여 DOM에 무언가를 저장할 수 있고 동일한 데이터(미래get
메서드 사용)를 가져와 해당 사용자가 아직 페이지에 있었는지 확인할 수 있기 때문에 매우 편리합니다.사용 사례
구성 요소에서 사용자 지정 함수
announceToast()
가 호출될 때 트리거되는 토스트 알림이 있다고 가정합니다. 또한 최근에 새로운 정보로 업데이트되었다고 가정합니다.app.component.ts
파일에서 최신 게시물을 나타내는 값을 보유하기 위해 속성(문자열 유형으로)을 초기화했습니다.export class AppComponent implements OnInit {
currentToast = 'Robots vs. Humans';
}
이제 구성 요소가 초기화되는 시기를 확인하여
localStorage
(문자열 유형)라는 개체 키가 blog
에 있는지 확인할 수 있습니다.export class AppComponent implements OnInit {
currentToast = 'Robots vs. Humans';
ngOnInit { // When the app initializes
// If the localStorage object key 'blog' has a value that does not match the currentToast string
if (localStorage.getItem('blog') !== this.currentToast) {
// Then we will clear localStorage altogether
localStorage.clear();
// We will trigger the new announcement toast
this.announceToast();
// And we'll set the 'blog' key to have the new current value
localStorage.setItem('blog', this.currentToast);
}
}
}
// If it does match, then we will do nothing and the value we set will continue to sit in localStorage under that key
즉, 결국 currentToast 속성의 값을 '로봇 대 인간'이 아닌 값으로 변경하면 구성 요소가 자동으로 이를 평가하고 개체를 지우고 새 값으로 대체합니다(새 토스트를 트리거하는 동안). .
이제 사용자가 매번 새로운 토스트를 볼 수 있도록 하나의 문자열만 업데이트하면 됩니다(이전 키 값 쌍으로 localStorage 개체를 오염시키지 않음).
Reference
이 문제에 관하여(사용자 방문 기억을 위한 로컬 저장소 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/riapacheco/using-local-storage-for-remembering-user-visits-coe텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)