Angular待办事项应用3
隔离业务逻辑
接着上一节,业务逻辑应该复古牛仔单独的service中,我们在todo文件夹中建立TodoService
ng g s todo/todo
引入UUID包
todo中id要唯一,一个是采用一个自增长数列,一个是采用随机生成的一组不可能重复的字符序列,常见的就是UUID
npm install --save angular2-uuid
安装成功:
修改id类型
export class Todo { id:string; desc:string; completed:boolean; }
修改service
import { Injectable } from '@angular/core'; import { Todo } from "./todo.model"; import { UUID } from "angular2-uuid"; @Injectable() export class TodoService { todos:Todo[]=[]; addTodo(todoItem:string):Todo[]{ let todo={ id:UUID.UUID(), desc:todoItem, completed:false }; this.todos.push(todo); return this.todos; } constructor() { } }
组件注入依赖service
import { Component, OnInit } from '@angular/core'; import { Todo } from "./todo.model"; import { TodoService } from "./todo.service"; @Component({ selector: 'app-todo', templateUrl: './todo.component.html', styleUrls: ['./todo.component.css'], providers:[TodoService] }) export class TodoComponent implements OnInit { todos:Todo[]=[]; desc=''; addTodo(){ this.todos=this.service.addTodo(this.desc); this.desc=''; } constructor(private service:TodoService) { } ngOnInit() { } }
安装插件(可选)
为了清晰看到成果,我们为chrome浏览器安装一个插件,在chrome地址栏输入
chrome://extensions/
下载一个“Angury”插件安装即可,然后按F12键调出开发者工具,里面有一个Angury的tab
ok!