ng service(服务)
创建服务命令:ng g service services/+服务名
使用服务的注意事项:
使用(services)服务需要在app.,module.ts(根模块)中引用并配置
- import { storageService } form './services/storage.service';
- 在providers中进行配置[storage.service]
- 那个页面在那个页面在进行一次引用 import { storageService } form '../../services/storage.service
- 声明方式:
- 方法一 var storage = new storages.service();
- 方法二 在constructor 中使用 constructor(public storage:storageservice){ let s = this.storage.get(); console.log(s);}
constructor(public storage:stroageservice)此句等同于storage= new storageservice()
this.storage.get()是声明调用服务storage中的get方法
public storage:storageservice中的storageservice必须和引入的类名相同
storage.service中
set(key:string,value:any){
loacalstorage.setitem(key,json.stringify(value));
}
get(key:string){
return Json.parse(localStorage.getItem(key))
}
remove(key:string){
localstorage.removeItem(key);
}