Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular 2服务本地存储_Javascript_Html_Angular_Local Storage - Fatal编程技术网

Javascript Angular 2服务本地存储

Javascript Angular 2服务本地存储,javascript,html,angular,local-storage,Javascript,Html,Angular,Local Storage,我正在尝试使用localstorage在服务中执行ToDoList add.component.ts export class AddComponent implements OnInit { item: Item[]; constructor( private router: Router, private itemService: ItemService) { } addTodo() { this.itemSe

我正在尝试使用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() {}

}
@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);
    }
}
export class Item {
    id: number;
    title: string;
    message: string;
}
<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>
item.service.ts

export class AddComponent implements OnInit {
    item: Item[];
    constructor(
        private router: Router,
        private itemService: ItemService) {
    }

    addTodo() {
        this.itemService.save();
        this.router.navigate(['./list']);
    }

   ngOnInit() {}

}
@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);
    }
}
export class Item {
    id: number;
    title: string;
    message: string;
}
<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

export class AddComponent implements OnInit {
    item: Item[];
    constructor(
        private router: Router,
        private itemService: ItemService) {
    }

    addTodo() {
        this.itemService.save();
        this.router.navigate(['./list']);
    }

   ngOnInit() {}

}
@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);
    }
}
export class Item {
    id: number;
    title: string;
    message: string;
}
<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,它会工作!但是,如果一个用户尝试将其作为一项服务来执行,我会遇到一个错误:
异常:未捕获(承诺中):错误:DI错误:DI错误

我不知道该怎么办。我在寻找如何做到这一点,但我没有找到一个对我有帮助的答案


有人知道如何修复它吗?

Localstorage不是一种角度服务。它只是一个控制浏览器本地存储的本地JS对象。因此你不能注射它。如果您想拥有服务功能,可以将本机
localstorage
包装成一个角度
LocalStorageService

您不想将
Item
注入
ItemService
中。您确实希望有一个get函数,它接受一个
项作为参数,并从本地存储中检索它。

正如PierreDuc所说,本地存储是用户浏览器的功能。据介绍,它应该适用于所有主要的浏览器

因为它具有浏览器功能,而不是角度的一部分,所以不需要注入。 有关如何使用localStorage的更多信息,您可以阅读


如果你仍然想使用它作为一个角度服务,我建议你使用

谢谢你的回答!我将尝试将其包装为
LocalStorageService
,它应该来自2.0版及更高版本