1.创建服务

打开命令窗口,cd到项目目录下,输入  ng g service myData1  回车 创建服务,如下图所示:

这样就成功创建了服务,此时,可以在项目的app文件夹下生成了两个service文件,

2.引入注册服务

服务创建好之后,要先引入注册之后才能用。

首先要在app.module.ts里:

引入     import { MyDataService } from './my-data.service';

注册      providers:[MyDataService];

app.module.ts整体代码如下:
import { NgModule }      from '@angular/core';//引入angular核心模块
import { BrowserModule } from '@angular/platform-browser'; //浏览器解析
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here //引入组件
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { NewsComponent } from './components/news/news.component'; //1.引入服务 注册服务
import { MyDataService } from './my-data.service'; @NgModule({
imports: [ //配置模块 /*引入模块 请求数据模块*/
BrowserModule,
FormsModule // <-- import the FormsModule before binding with [(ngModel)]
],
declarations: [ //声明 注册 组件 所有自定义的组件都要在这里声明
AppComponent,
HeaderComponent,
NewsComponent
],
providers:[MyDataService], /*服务 工具*/
bootstrap: [ AppComponent ] //启动模块 /*加载根组件*/
})
export class AppModule { } //暴露跟模块
app.module.ts里引入注册之后,还需要在用到服务的地方引用,我写的demo是在news组件里用到了MyDataService服务,所以就在news.component.ts里引入
//要用服务 1.需要在app.module.ts 引入和注册    2.在使用的地方引入

import { MyDataService } from '../../my-data.service';

这样就可以在news.component.ts中使用MyDataService服务了;

3.使用服务

使用服务就是把服务实例化,在news.component.ts中用构造函数来实例化我们定义的服务:

  constructor(private  storage:MyDataService) {
console.log(this.storage);
this.news = this.storage.getItem('msgList') || [];
}

这样就可以使用服务了。

我这里写了一个小demo,使用服务实现数据的缓存处理:

html:

<h3>{{newsTitle}}</h3>
<input type="text" [(ngModel)]="currentMsg"><button (click)="addList()">增加+</button>
<ul>
<li *ngFor="let item of news;let key =index">
{{item}}------<button (click)="delete(key)">删除</button>
</li>
</ul>

news.component.ts:

import { Component, OnInit } from '@angular/core';

//要用服务 1.需要在app.module.ts 引入和注册    2.在使用的地方引入

import { MyDataService } from '../../my-data.service';

@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit { public news = [];
public newsTitle = '填写个人信息,添加到列表';
public currentMsg; constructor(private storage:MyDataService) { this.news = this.storage.getItem('msgList') || [];
} ngOnInit() { } addList() {
this.news.push(this.currentMsg);
this.storage.setItem('msgList',this.news);
}
delete(i){
this.news.splice(i,1);
this.storage.setItem('msgList',this.news);
} }

my-data1.sevice.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class MyDataService { constructor() { } setItem(key,value){
localStorage.setItem(key,JSON.stringify(value));
}
getItem(key){
return JSON.parse(localStorage.getItem(key));
}
removeItem(key){
localStorage.removeItem(key);
} }
 

angular2.0---服务Service,使用服务进行数据处理的更多相关文章

  1. 安卓第十三天笔记-服务(Service)

    安卓第十三天笔记-服务(Service) Servcie服务 1.服务概念 服务 windows 服务没有界面,一直运行在后台, 运行在独立的一个进程里面 android 服务没有界面,一直运行在后台 ...

  2. Angular.js之服务与自定义服务学习笔记

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 在 CentOS7 上将自定义的 jar 包注册为 linux 服务 service

    在 CentOS7 上将自定义的 jar 包注册为 linux 服务 service 1.在 /etc/rc.d/init.d/ 目录下创建一个名字和服务名完全相同的 shell 脚本文件 joyup ...

  4. Windows Service插件服务开源

    WindowsService 插件服务是一个为简化NTService开发和打包程序,提供插件开发的方式进行动态加入或删除业务. 插件式服务程序的由来,在系统维护的过程中,根据企业的要求经常要进行一些周 ...

  5. 安卓服务(Service)的两种开启方式以及服务的生命周期

    安卓中服务的开启方式 一:採用start的方式开启服务 调用函数:startService(Intent)->onCreate()->onStart()/onStartCommand()- ...

  6. 服务 Service 基本介绍

    Activity public class MainActivity extends ListActivity {     private boolean flag;//是否开启线程     publ ...

  7. Android服务Service总结

    转自 http://blog.csdn.net/liuhe688/article/details/6874378 富貴必從勤苦得,男兒須讀五車書.唐.杜甫<柏學士茅屋> 作为程序员的我们, ...

  8. Android学习笔记--服务(Service)

    1.服务概述 1.服务是Android四大组件之一,在使用上可以分为本地服务和远程服务,本地服务是指在不影响用户操作的情况下在后台默默的执行一个耗时操作,例如下载,音频播放等.远程服务是指可以供其他应 ...

  9. BZOJ 1820: [JSOI2010]Express Service 快递服务( dp )

    dp(i,j,k)表示在处理第i个业务, 另外2个在j,k处. 第一维可以滚动... --------------------------------------------------------- ...

随机推荐

  1. Android NDK开发Crash错误定位

    在Android开发中,程序Crash分三种情况:未捕获的异常.ANR(Application Not Responding)和闪退(NDK引发错误).其中未捕获的异常根据logcat打印的堆栈信息很 ...

  2. Centos之文件搜索命令find

    find [搜索范围] [搜索条件] #搜索文件 find / -name install.log #避免大范围搜索,会非常耗费系统资源 #find是在系统当中搜索符合条件的文件名.如果需要匹配, 使 ...

  3. Hbuilder用ajax连接eclipse中的servlet例子以及注意事项

    今天用前端神器Hbuilder连接eclipse中的servlet,真是费了九牛二虎之力,才把问题解决 Hbuilder中的代码: test.html <!DOCTYPE html> &l ...

  4. 一元运算符 +,可用于将变量转换为数字;如果变量不能转换,它仍然会是一个数字,但值为 NaN (不是一个数字)

    一元运算符,可用于将变量转换为数字: var y = "5"; var x = + y; console.log(typeof y);//string 类型 console.log ...

  5. 原生Js弹窗插件|web弹出层组件|对话框

    wcPop.js 是一款基于原生javascript开发的前端 web版 弹窗组件,遵循原生 H5/css3/JS 的书写规范,简单实用.拿来即用(压缩后仅10KB).已经兼容各大主流浏览器.内含多种 ...

  6. Scala 中的foreach和map方法比较

    Scala中的集合对象都有foreach和map两个方法.两个方法的共同点在于:都是用于遍历集合对象,并对每一项执行指定的方法.而两者的差异在于:foreach无返回值(准确说返回void),map返 ...

  7. java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification

    ListView UI重绘时触发layoutChildren, 此时会校验listView的mItemCount与其Adapter.getCount是否相同,不同报错. ListView.layout ...

  8. 【C#小知识】C#中一些易混淆概念总结(八)---------解析接口 分类: C# 2014-02-18 00:09 2336人阅读 评论(4) 收藏

     这一篇主要来解析关于面向对象中最总要的一个概念--接口. 对于接口来说,C#是有规定使用Interface关键字来声明接口.它的声明是和类一致的.可以说接口就是一个特殊的抽象类.如下代码: cl ...

  9. 解析ASP.NET Mvc开发之EF延迟加载 分类: ASP.NET 2014-01-04 01:29 4017人阅读 评论(1) 收藏

    目录: 从明源动力到创新工场这一路走来 解析ASP.NET WebForm和Mvc开发的区别 解析ASP.NET 和Mvc开发之查询数据实例 ----------------------------- ...

  10. Eclipse打不开 提示an error has occurred.see the log file

    有时由于Eclipse卡死,强制关闭之后会出现打不开的情况.弹窗提示: 查看log文件,发现有这样的信息:  !MESSAGE The workspace exited with unsaved ch ...