Angular 角度类型错误:无法创建属性';x';关于字符串';[对象对象]';
代码: 我运行此测试:Angular 角度类型错误:无法创建属性';x';关于字符串';[对象对象]';,angular,typescript,Angular,Typescript,代码: 我运行此测试: import { NgModule } from '@angular/core'; @NgModule({ }) export class LocalStorageService { private store; constructor() { this.store = {} console.log("constructor", this.store) } getItem(key: string)
import { NgModule } from '@angular/core';
@NgModule({
})
export class LocalStorageService {
private store;
constructor() {
this.store = {}
console.log("constructor", this.store)
}
getItem(key: string) {
console.log("get", this.store)
return this.store[key];
}
setItem(key: string, value: string) {
console.log("set", this.store)
this.store[key] = value;
}
}
执行测试时,我得到2个日志:
LOG:'constructor',对象{}
LOG:'set','[object]'
似乎有东西将store
属性从对象强制转换为字符串,这是我得到的错误:TypeError:无法在字符串“[object object]”上创建属性“x”
这里发生了什么?我认为对象是空的,localstorage不存储对象 按F12>转到控制台>执行localStorage.setItem(“x”,{name:'renato'}),然后尝试获取值>localStorage.getItem(“x”) 结果将是“[对象]”
beforeEach(() => {
// omit
storage = TestBed.get(LocalStorageService);
spyOn(localStorage, 'getItem').and.callFake(storage.getItem);
spyOn(localStorage, 'setItem').and.callFake(storage.setItem);
});
it('should store local status', () => {
localStorage.setItem("x", "y");
});