angularcli 第七篇(service 服务)

在组件中定义的信息是固定的,假设另外一个组件也需要用到这些信息,这时候就用到服务,实现数据共享

1、创建服务到指定目录下:    

  • ng g service services / storage

2、app.module.ts里面引入创建的服务

  • import { StorageService } from '. /service / storage.service';
  • @NgModule里面的providers依赖注入服务 provides:  [ StorageService ] ,

 

3、使用的页面引入服务、注册服务

  • import { StorageService } from '../. /service / storage.service';
  • private storage : StorageService   注入到构造函数

到这里todolist 组件就可以使用 storage.service 服务里的数据了

todolist.component.ts界面:

export class TodolistComponent implements OnInit {

  public username:any='';
  public list=[];

  //private storage:StorageService  依赖注入服务
  constructor(private storage:StorageService) { 

      console.log(this.storage);

      // this.storage.setItem('username','张三');

      // alert(this.storage.getItem('username'));
  }

  ngOnInit() {

      //每次刷新获取storage里面 todolist的值

      var todolist=this.storage.getItem('todolist');
      if(todolist){

        this.list=todolist;
      }
     
  }

  addData(e){

    //1.从storage获取  todolist的数据

    //2.如果有数据,拿到这个数据,然后把新数据和这个storage数据拼接,重新写入

    //3.如果没有数据  直接给storage写入数据


      if(e.keyCode==13){

          var obj={  /*每次增加的一个对象数据*/
            username:this.username,
            status:1
          }

          var todolist=this.storage.getItem('todolist');

          if(todolist){

            todolist.push(obj);

            //如果有数据,拿到这个数据,然后把新数据和这个storage数据拼接,重新写入
            this.storage.setItem('todolist',todolist);
            
          }else{

            //3.如果没有数据  直接给storage写入数据
              var arr=[];

              arr.push(obj);

              this.storage.setItem('todolist',arr);
          }

          this.list.push(obj);
          this.username='';
      }

    // console.log(e);
  }
  deleteData(key){

      // alert(key);

      this.list.splice(key,1);   /*删除数组的数据*/
  }

  changeData(key,status){ /*改变状态*/

      this.list[key].status=status;

      this.storage.setItem('todolist',this.list);
  }
}
Storage.Service.ts界面:

export class StorageService {

  constructor() {   /*构造函数*/
  }

  setItem(key,value){
      localStorage.setItem(key,JSON.stringify(value))
  }

  getItem(key){
      return JSON.parse(localStorage.getItem(key));
  }

  removeItem(key){
    localStorage.removeItem(key);
  }
}

 

猜你喜欢

转载自www.cnblogs.com/luwanying/p/9419881.html