简体   繁体   中英

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. I have also another component named navbar with methods like logout() . Now I want to clear my filter out of the sessionStorage if I click on logout() .

I tried this in my navBar Component:

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

I also tried to implement this in my projectComponent :

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

And put this in the navbarComponent Constructor:

private project: Projects;

and use in my navbarComponent logout method a function call to let the project delete the session items.

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"

Can someone please help me?

You can simply create an Angular service ,

The service looks like this

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

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

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

Usage #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

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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