angular创建服务

创建服务

ng g service my-new-service 创建到指定目录下面 ng g service services/storage

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

import { StorageService } from './services/storage.service';

NgModule 里面的 providers 里面依赖注入服务

@NgModule({ 
declarations: [ AppComponent, HeaderComponent, FooterComponent, NewsComponent, TodolistComponent ],
imports: [ BrowserModule, FormsModule ],
providers: [StorageService], //注入服务
bootstrap: [AppComponent] 
})
export class AppModule { }

使用的页面引入服务,注册服务

import { StorageService } from '../../services/storage.service';
constructor(private storage: StorageService) { }

使用

addData(){
 // alert(this.username); 
this.list.push(this.username); 
this.storage.set('todolist',this.list); 
}
removerData(key){ 
console.log(key);
 this.list.splice(key,1); 
this.storage.set('todolist',this.list); 
}
/*
1、ng g service services/storag
2、app.module.ts 里面引入创建的服务 并且声明
import { StorageService } from './services/storage.service'
providers: [StorageService]
3、在用到的组件里面
      //引入服务
      import { StorageService } from '../../services/storage.service';
      //初始化
      constructor(public storage:StorageService) { 
          let s=this.storage.get();
          console.log(s);
      }
*/
import { Component, OnInit } from '@angular/core';
//引入服务
import { StorageService } from '../../services/storage.service';
/*
不推荐
var storage=new StorageService();
console.log(storage);
*/
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
  public keyword:string;
  public historyList:any[]=[];
  constructor(public storage:StorageService) { 
  }
  ngOnInit() {
    console.log('页面刷新会触发这个生命周期函数');
    var searchlist:any=this.storage.get('searchlist');
    if(searchlist){
      this.historyList=searchlist;        
    }
  }
  doSearch(){
    if(this.historyList.indexOf(this.keyword)==-1){
      this.historyList.push(this.keyword);
      this.storage.set('searchlist',this.historyList);
    }    
    this.keyword='';    
  }
  deleteHistroy(key){
      this.historyList.splice(key,1);
      this.storage.set('searchlist',this.historyList);
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • core package 概要:Core是所有其他包的基础包.它提供了大部分功能包括metadata,templa...
    LOVE小狼阅读 2,675评论 0 3
  • Angular介绍 Angular安装、创建项目、目录结构、组件、服务 创建组件、绑定数据、绑定属性、数据循环、条...
    地瓜粉丝阅读 556评论 0 2
  • 一、安装最新版本的 nodejs 注意:请先在终端/控制台窗口中运行命令 node -v 和 npm -v, 来验...
    liuguangsen阅读 2,157评论 0 1
  • NgModule参考手册 选项说明providers:在当前模块的注入器中可用的一组可注入对象。@Componen...
    前端菜篮子阅读 1,045评论 0 0
  • 前言 作为一名后端开发,涉及到前端时可能更注重JavaScript和TypeScript的学习与使用,至于html...
    6plus阅读 968评论 0 0