Angular4.x创建使用服务

一、 Angualr CLI创建服务

Scaffold Usage
Component ng g component my-new-component
Service ng g service my-new-service

二、创建服务命令

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

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

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

  1. import { StorageService } from './services/storage.service';
  1. NgModule 里面的providers 里面依赖注入服务
  1. @NgModule({
  2. declarations: [
  3. AppComponent,
  4. HeaderComponent,
  5. FooterComponent,
  6. NewsComponent,
  7. TodolistComponent ],
  8. imports: [
  9. BrowserModule,
  10. FormsModule
  11. ],
  12. providers: [StorageService],
  13. bootstrap: [AppComponent]
  14. })
  15. export class AppModule { }

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

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

使用

  1. addData(){
  2. // alert(this.username);
  3. this.list.push(this.username);
  4. this.storage.set('todolist',this.list);
  5. }
  6. removerData(key){
  7. console.log(key);
  8. this.list.splice(key,1);
  9. this.storage.set('todolist',this.list);
  10. }
作者:admin  创建时间:2018-06-18 17:00
 更新时间:2018-06-18 17:08