创建服务 : ng g service services(服务的目录文件名)/storage
src/app/会生成一个services的文件目录里面包含两个文件
storage.service.spec.ts
storage.service.ts
在storage.service.ts中写公共的方法
import {Injectable} from '@angular/core';
@Injectable({
providedIn:'root'
})
export class StorageService{
constructor(){}
fun(){
return 'angular service'
}
}
在app.module.ts中引入服务
//双向绑定
import {FormsModule} from '@angular/forms';
//引入配置服务
import {StorageService} from './services/storage.service.ts';
@NgModule({
declarations:[ //组件
AppComponent,
],
imports:[ //模块
BrowserModule,
FormsModule,//双向绑定
],
providers:[ //服务
StorageService,
],
bootstrap:[AppComponent]
})
export class AppModule{}
在要使用服务的组件中 引入服务
import {Component,OnInit} from '@angular/core';
//注意 引入的路径
import {StorageService} from '../../services/storage.service.ts';
@Component({
selector:'app-home',
templateUrl:'./home.component.html',
styleUrls:['./home.component.scss']
})
export class HomeComponent implements OnInit{
constructor(public storage:StorageService){
let s=this.storage.fun()
console.log(s) //'angular service'
}
OnInit(){}
}