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)
}
}