简体   繁体   English

在 Angular 中使用 getter 和 setter 的 TypeError

[英]TypeError using getter and setter in Angular

I am using getter and setter to set a field from the web cache, but I get the TypeError when I try to use the setter for example.我正在使用 getter 和 setter 从 web 缓存中设置一个字段,但是当我尝试使用 setter 时出现TypeError The error is:错误是:

ERROR TypeError: this.saveCache is not a function

The getter and setter are below: getter 和 setter 如下:

    get saveCache (): any {
        if (localStorage.getItem('saveCache') === null) {
          return null;
        }
        return JSON.parse(localStorage.getItem('saveCache'));
      }
      
      set saveCache(value:any) {
        localStorage.setItem('saveCache', JSON.stringify(value));
      }

When I try to set the saveCache field, I get the above error.当我尝试设置saveCache字段时,出现上述错误。 How can I solve this issue?我该如何解决这个问题?

I added an example here with the error:我在这里添加了一个错误示例:

https://stackblitz.com/edit/angular-ivy-cryfvb?file=src%2Fapp%2Fapp.component.ts

A setter has to be used as below:必须使用 setter,如下所示:

this.saveCache = this.fruits;

and not this.saveCache(this.fruits);而不是this.saveCache(this.fruits);

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

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