Angular: 从localStorage中拉取值并显示值

Angular: Pull value from localStorage and display values

我正在使用多 select mat-button-toggle-group 在 localStorage 中填充一个列表,但是当我尝试在我的页面上显示该值时,它返回为空。我错过了什么?


我有一个带有(更改)触发器和默认值的 mat-button-toggle-group [(value)]="productCookie"

<mat-button-toggle-group #group="matButtonToggleGroup" name="productSelect" aria-label="Font Style" multiple [(value)]="productCookie (change)=productFilter(group.value)>
    <mat-button-toggle *ngFor="let product of products" [value]="product.name">
      <a>{{product.name}}</a>
    </mat-button-toggle>
</mat-button-toggle-group>

在更改时设置 localStorage 中的值 (change)=productFilter(group.value)

productFilter($event){
  console.log("productFilter event value: " + $event)
  this.selectedProductFilter = $event

  // Testing
  console.log(this.selectedProductFilter)
  
  localStorage.setItem('productFilter', JSON.stringify(this.selectedProductFilter));
}

控制台输出 在 selecting 3 个选项之后:

productFilter event value: Wii,Xbox,Playstation3
gaming-report.component.ts:280 (3) ["Wii", "Xbox", "Playstation3"]

然后我可以通过控制台 -> 应用程序 -> 本地存储验证值是否已设置

productFilter   ["Wii", "Xbox", "Playstation3"]

所以现在我尝试提取这些值:

ngOnInit() {
 this.getProductCookie();
}



getProductCookie(){
 if (localStorage.getItem('productFilter') === null){
  console.log("No filters found in localStorage")  
 }
 else{
  this.productCookie = JSON.parse(localStorage.getItem('productFilter'));
  console.log("localStorage Data Type: " + typeof this.productCookie)  //object      
  console.log("localStorage: " + this.productCookie)  // Wii,Xbox,Playstation3

 }  
}

控制台输出:

localStorage Data Type: object
localStorage: Wii,Xbox,Playstation3

正在提取该值,并存储在 this.productCookie 中,因此我应该可以在我的 html

中使用 productCookie
<div>
    testing:
    {{productCookie|json}}
</div>

但它不显示任何内容 productCookie value is empty

编辑:将 {{productCookie}} 更改为 {{productCookie|json}} 现在正在打印

testing: []

直到我开始 selecting 选项 Selecting an option updates productCookie value

编辑:现在打印

testing: [ "Wii", "Xbox", "Playstation3" ]

我做错了什么阻止此 localStorage 值显示在 html 中?

上面的代码是正确的,我的本地环境有问题。

查看 https://stackblitz.com/edit/working-example-localstorage-default-buttons?file=src/app/button-toggle-appearance-example.ts