Angular--(三)服务Service

服务Service的作用

  • 共享数据  在组件中定义的信息是固定的,假设另外一个组件也需要用到这些信息,这时候就用到服务,实现共享数据和方法

  • 封装方法  组件不应该直接获取或保存数据,它们不应该了解是否在展示假数据。 它们应该聚焦于展示数据,而把数据访问的职责委托给某个服务。

  • 数据持久化  Service 可以从任何地方获取数据:Web 服务、本地存储(LocalStorage)或一个模拟的数据源

创建服务命令  ng g service services/storage

服务的使用

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

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

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

providers:[StorageService],

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

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

4、使用具体方法

this.storage.set('dd',this.list);

猜你喜欢

转载自blog.csdn.net/fn512613/article/details/90178018
今日推荐