javascript - Angular 2 接口(interface)和 LocalStorage 服务

标签 javascript html angular local-storage

我尝试使用 localstorage 作为服务来保存一些数据,因此我创建了一个接口(interface)和一个组件来调用两者(LocalStorage 服务和接口(interface))。

界面:

export interface Items {
    id: number;
    title: string;
    message: string;
    done: boolean;
}

服务:

@Injectable()
export class LocalStorageService {

    saved: string = localStorage.getItem('currentItem');
    currentItem: string = (localStorage.getItem('currentItem') !== null) ? JSON.parse(this.saved) : [  ];
    todos: any = this.currentItem;

    save(id, title, message, done) {
        this.todos.push({
            id: id,
            title: title,
            message: message,
            done: false
        });

        localStorage.setItem('currentItem', JSON.stringify(this.todos));
    }

}

组件:

export class AddComponent implements OnInit {

    todoForm: FormGroup;

    currentItem: string;
    todos: any;

    constructor(fb: FormBuilder,
                private router: Router,
                private storageService: LocalStorageService,
                private items: Items) {
        this.currentItem = (localStorage.getItem('currentItem') !== null) ? JSON.parse(localStorage.getItem('currentItem')) : [  ];
        this.todos = this.currentItem;

        this.todoForm = fb.group({
            id: '',
            title: '',
            message: '',
            done: ''
        });
    }

    addTodo(event) {
        console.log(this.todoForm.value);
        this.storageService.save(this.items.id, this.items.title, this.items.message, this.items.done)
        this.router.navigate(['./list']);
    }

   ngOnInit() {}

}

HTML:

<div class="container">
    <form (submit)="addTodo($event)">

        <div class="form-group">
            <label>Id:</label>
            <input [(ngModel)]="id" class="textfield form-control" name="id" />
        </div>

        <div class="form-group">
            <label>Titulo:</label>
            <input [(ngModel)]="title" class="textfield form-control" name="title">
        </div>

        <div class="form-group">
            <label>Mensagem:</label>
            <input [(ngModel)]="message" class="textfield form-control" name="message">
        </div>

        <button type="submit" class="btn btn-success">Salvar</button>
    </form>
</div>

当我尝试访问 html 文件时出现很多错误。

我正在对 Angular 2 进行概念验证,我想使用 localStorage 作为服务和接口(interface)。我知道我不需要 localStorage 作为服务来完成它的工作,但在一个大项目中我认为我需要将它用作服务。

我要开发的项目必须离线工作,因此为了在所有组件中调用 localStorage,我创建了这个 localStorage 服务。

有人知道如何解决这个问题吗?

使用接口(interface)和 LocalStorage 作为服务是开发大项目的最佳方式吗?

最佳答案

您的代码中有很多错误。我可以首先完全跳过 localStorage。您可以按原样使用该服务,无需混合到本地存储中。在现实生活中的应用程序中,您将进行 http 调用来检索数据,如下所示:

addTodo(todo) {
  //make api request, handle response, return result to component
}

getTodos() {
  //make api request, handle response, return result to component
}

您可以对您的应用程序执行完全相同的操作,但有一个本地数组,例如 todos ,因此您的服务可能如下所示:

@Injectable() 
export class LocalStorageService {

  todos: Item[];

  constructor() {
    // lets add one item by default
    this.todos = [{id:1,title:'title1',message:'message1',done:false}]
  }

  getTodos() {
    return this.todos;
  }

  addTodo(todo) {
    this.todos.push(todo)
  }
}

您可以在离线 session 期间执行这些待办事项! :)

<小时/>

然后转到您的组件,您遇到的错误:

  1. 请勿注入(inject) items对于您的构造函数,构造函数仅适用于提供者
  2. 您正在将模板驱动表单与响应式(Reactive)表单混合在一起
  3. 在您的addTodo中您所指的函数例如 this.items.id ,但在你的组件中没有任何地方有 item

好吧,让我们看看你的表单,这里我将你的表单更改为模板驱动,所以删除 FormGroup共。您也不需要双向绑定(bind)。您可以构建表单,以便从表单中获取的对象具有正确的格式,以便可以按原样推送到待办事项。您可以通过使用 name 在表单中实现此目的属性与 ngModel 一起,它绑定(bind)您的表单。 name属性将成为对象中的键,当然您在表单中输入的值将成为键对应的值。所以你的表单看起来像这样:

<form #myForm="ngForm" (ngSubmit)="addTodo(myForm.value)">
  <label>Id:</label>
  <input name="id" ngModel />
  <label>Titulo:</label>
  <input name="title" ngModel />
  <label>Mensagem:</label>
  <input name="message" ngModel />
  <button type="submit">Salvar</button>
</form>

这会产生( myForm.value )一个像这样的对象:

{
  "id": "",
  "title": "",
  "message": ""
}

...当它为空时。这里你还有另外一项属性(property)done在您的对象中,因此在提交后,在将这个新待办事项插入数组之前,让我们添加该属性键:

addTodo(value) {
  // push the missing value to object
  value.done = false;
  // call method in service to save the new todo
  this.storageService.save(value)
  // update the list of todos
  this.todos = this.storageService.getTodos();
}

请务必阅读官方文档中有关 Angular 的内容,他们有非常好的教程。根据您此处的代码,请查看 Services ,它使用本地模拟数据,正如您想要的那样。另请参阅 Forms ,模板驱动表单和模型驱动表单的区别!

作为奖励,这里有一个 Plunker 一起玩:)

关于javascript - Angular 2 接口(interface)和 LocalStorage 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863489/

相关文章:

javascript - 获取 : POST JSON data

javascript - Haxe -> JS switch 语句分支错误(Haxe -> 相同代码的 Flash 工作正常),为什么?

javascript - 超链接图像未显示在 Chrome 扩展程序上

html - 如何在导航菜单的下拉菜单中获取图像以显示

javascript - Angular 2.0 和 ng 风格

javascript - 使用同一按钮在窗口重新加载后调用函数

javascript - 如何在 MVC 中实现 <ul> nav-tabs 使其表现得像 <a data-toggle ="tab"href ="#">?

html - CSS - 当 .b :hover? 时,我可以更改 div .a 背景色吗

angular - 如何在 ionic 2 中生成和显示二维码

angular Testbed overrideModule 不工作