Angular中的服务 以及自定义服务-数据持久化

Angular采用模块化、组件化的开发方式

组件之间的方法不能相互调用,一些公共的功能封装到服务里面,各组件调用服务里面的方法

服务之间可以相互调用;服务不能调用组件

 

 二、 创建服务命令

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

三、app.module.ts (根组件)里面引入创建的服务

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

import { StorageService } from './services/storage.service';

2. NgModule 里面的 providers 里面依赖注入服务

@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent,
TodolistComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }

四、(其他组件)使用的页面引入服务,注册服务

import { StorageService } from '../../services/storage.service';

constructor(private storage: StorageService) {
}

数据持久化

ngOnInit()生命周期函数
引入服务里面的数据/函数
在服务里面定义getData()方法
 ngOnInit(){
let data = this.storage.getData();
console.log(data)
}
 
 
 
原文地址:https://www.cnblogs.com/foremostxl/p/12937894.html