简体   繁体   English

如何在其他组件中使用 sessionStorage.clear()?

[英]how to use sessionStorage.clear() in other component?

I use Angular 4 and fill some filter data in my sessionStorage in my project component to store them during my browser session.我使用 Angular 4 并在我的项目组件的sessionStorage中填充一些过滤器数据,以便在我的浏览器 session 期间存储它们。 I have also another component named navbar with methods like logout() .我还有另一个名为 navbar 的组件,其中包含logout()等方法。 Now I want to clear my filter out of the sessionStorage if I click on logout() .现在,如果单击logout() ,我想从sessionStorage中清除我的过滤器。

I tried this in my navBar Component:我在我的navBar组件中尝试了这个:

logout (): void {
  sessionStorage.clear();
}

I also tried to implement this in my projectComponent :我也尝试在我的projectComponent中实现这一点:

import { Component, OnInit, Injectable } from '@angular/core';
...
public deleteFilter(){
  sessionStorage.clear();
}

And put this in the navbarComponent Constructor:并将其放入navbarComponent构造函数中:

private project: Projects;

and use in my navbarComponent logout method a function call to let the project delete the session items.并在我的navbarComponent注销方法中使用 function 调用以让项目删除 session 项目。

logout (): void {
  this.project.deleteFilter();
}

But if I logout and login the filter are still stored.但是,如果我注销并登录,过滤器仍会被存储。 I can delete them directly in my browser with pressing f12 => "Application" => "clear Storage"我可以通过按 f12 => "Application" => "clear Storage" 在浏览器中直接删除它们

Can someone please help me?有人可以帮帮我吗?

You can simply create an Angular service ,您可以简单地创建一个Angular 服务

The service looks like this服务看起来像这样

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {
  constructor() {}

  public clear() {
    sessionStorage.clear();
  }
}

Usage #1用法 #1

import { Component, VERSION } from '@angular/core';
import { StorageService } from './storage.service';

@Component({
  selector: 'usage1',
  templateUrl: './usage1.component.html',
  styleUrls: ['./usage1.component.css']
})
export class Usage1Component {
  constructor(private storageService: StorageService) {
    // You can use the method like this
    this.storageService.clear();
  }
}

Usage #2用法 #2

import { Component, Input } from '@angular/core';
import { StorageService } from './storage.service';

@Component({
  selector: 'usage2',
  templateUrl: './usage2.component.html',
  styleUrls: ['./usage2.component.css']
})
export class Usage2Component {
  @Input() name: string;
  constructor(private storageService: StorageService) {
    // You can use the method like this
    this.storageService.clear();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM