【发布时间】:2018-07-02 15:34:31
【问题描述】:
我一直在尝试使用 localStorage 保存对象,但它不起作用。我是 Angular2 的新手。
这是我的 app.component 代码
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
text = [];
title = 'app works!';
passText(i) {
console.log(i);
localStorage.setItem('text', JSON.stringify(i));
}
}
这是我的 component.html 代码
<div>
<input type="text" name="" [(ngModel)]="text.text">
<input type="text" name="" [(ngModel)]="text.newData">
<button class="btn btn-primary" (click)="passText(text)">submit</button>
</div>
【问题讨论】:
-
您需要比“它不起作用”更具体。正在发生什么,应该发生什么?
-
console.log(i);是否显示结果? -
它正在本地存储中保存一个空对象
-
如果您想要一个对象,请尝试将
text = []更改为text = {} -
Core972,是的,结果显示为 [text: "mb nmb", newData: "nmdms"]
标签: javascript angular local-storage