ng g services services/storage
# 1 :创建服务
《storage.service.ts》:
import { Injectable } from '@angular/core';
@Injectable()
export class StorageService {
constructor() { }
setItem(key,value){
localStrage.setItem(key,JSON.stringify(value))
}
getItem(key){
return JSON.parse(localStrage.getItem(key));
}
removeItem(key){
localStorage.removeItem(key);
}
# 2: 引入服务
《app.modules.ts》:
import { StorageService } from './services/storage.service'; //注意路径
...
providers: [StorageService] //依赖注入服务
《todoList.component.ts》:
法1:【官方不推荐】
import { StorageService } from '../../services/storage.service';
export class TodoListComponent implement OnInit {
public storage = new StorageService();
public username:anu = '';
constructor() {
this.storage.setItem('username','xj');
}
}
法2:【官方推荐】 -- 使用页面引入服务,注册服务
import { StorageService } from '../../services/storage.service';
export class TodoListComponent implement OnInit {
public username:any = '';
constructor(private storage:StorageService) { // 依赖注入服务
alert( this.storage.getItem("username) );
}
}