我尝试使用localstorage在服务中执行ToDoList。
add.component.ts
export class AddComponent implements OnInit {
item: Item[];
constructor(
private router: Router,
private itemService: ItemService) {
}
addTodo() {
this.itemService.save();
this.router.navigate(['./list']);
}
ngOnInit() {}
}
item.service.ts
@Injectable()
export class ItemService {
private itemsUrl = 'items';
private headers = new Headers({'Content-Type': 'application/json'});
private todos: any;
private currentItem: any;
constructor(
private http: Http,
private item: Item) {
this.currentItem = (localStorage.getItem('currentItem')!==null) ? JSON.parse(localStorage.getItem('currentItem')) : [ ];
this.todos = this.currentItem;
}
save(): Promise<Item> {
return this.http
.post(this.itemsUrl, {headers: this.headers})
.toPromise()
.then((res: Response) => {
this.todos.push({
id: this.item.id,
title: this.item.title,
message: this.item.message,
done: false
});
this.todos.title = '';
this.todos.message = '';
localStorage.setItem('currentItem', JSON.stringify(this.todos))
return this.todos;
})
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.log('An error occured', error);
return Promise.reject(error.message || error);
}
}
item.ts
export class Item {
id: number;
title: string;
message: string;
}
add.component.ts
<div class="container">
<form (submit)="addTodo()">
<div class="form-group">
<label>Id:</label>
<input [(ngModel)]="id" class="textfield form-control" name="id">
</div>
<div class="form-group">
<label>Titulo:</label>
<input [(ngModel)]="title" class="textfield form-control" name="title">
</div>
<div class="form-group">
<label>Mensagem:</label>
<input [(ngModel)]="message" class="textfield form-control" name="message">
</div>
<button type="submit" class="btn btn-success">Save</button>
</form>
</div>
如果我在add.component.ts
中添加localstorage,它就可以了!但是,如果尝试将其作为服务进行尝试,则会出现错误:EXCEPTION: Uncaught (in promise): Error: DI Error Error: DI Error
我不知道该怎么做。我搜索了怎么做,但我找不到能帮到我的答案。
有谁知道如何修复它?
答案 0 :(得分:0)
Localstorage不是角度服务。它只是一个控制浏览器本地存储的本机JS对象。因此你不能注射它。如果您想拥有服务功能,可以将原始localstorage
换成角度LocalStorageService
答案 1 :(得分:0)
您不想将Item
注入ItemService
。你真的想要一个接受Item
作为参数的get函数,并从localStorage中检索它。
答案 2 :(得分:0)