Angular中的服务

Angular中的服务是独立于各个组件的,比如数据缓存功能,哪个组件需要使用,直接引用该服务即可。
创建服务的命令:

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

在app.module引入并且配置服务

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
// import { FormComponent } from './components/form/form.component';
import { FormsModule } from '@angular/forms';
import { SearchComponent } from './components/search/search.component';
import { TodolistComponent } from './components/todolist/todolist.component';
//引入服务
import { StorageService } from './services/storage.service';
@NgModule({
  declarations: [
    AppComponent,
    SearchComponent,
    TodolistComponent,
    
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [StorageService],//服务
  bootstrap: [AppComponent]
})
export class AppModule { }

在组件中使用该服务

import { Component, OnInit } from '@angular/core';
//引入服务
import { StorageService } from 'src/app/services/storage.service';
//实例化服务
var storage = new StorageService();

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less']
})
export class SearchComponent implements OnInit {

  constructor() {
    //使用服务
    storage.get();
   }
  public content:string='';
  public historyList:any[] = []; 
  ngOnInit(): void {
  }
  //列表中添加历史记录
  doSearch(){
    if(this.historyList.indexOf(this.content)==-1){
      this.historyList.push(this.content);
    }
    this.content = '';
    console.log(this.historyList);
  }
  //删除指定记录
  deleteHistory(key:any){
    alert(key)
    this.historyList.splice(key,1)
  }
}

以上步骤不推荐,以下为官方使用服务方法,在cibstructor()中使用constructor(public storage:StorageService)

import { Component, OnInit } from '@angular/core';
//引入服务
import { StorageService } from 'src/app/services/storage.service';
//实例化服务,不推荐
// var storage = new StorageService();

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less']
})
export class SearchComponent implements OnInit {
//推荐使用方法
  constructor(public storage:StorageService) {
    //使用服务
    // storage.get();
    this.storage.get();
   }
  public content:string='';
  public historyList:any[] = []; 
  ngOnInit(): void {
  }
  //列表中添加历史记录
  doSearch(){
    if(this.historyList.indexOf(this.content)==-1){
      this.historyList.push(this.content);
    }
    this.content = '';
    console.log(this.historyList);
  }
  //删除指定记录
  deleteHistory(key:any){
    alert(key)
    this.historyList.splice(key,1)
  }
  

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值