我对 Angular2 很陌生,正在尝试构建一个 Todo 应用程序。
这是我的文件结构:
My todo.service.ts代码(里面shared folder)
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { ITodo } from './todo.model';
@Injectable()
export class TodoService {
constructor(private http: Http){}
getTodos(): Promise<ITodo[]> {
return this.http.get('api/todos')
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
addTodo(todo: ITodo): Promise<ITodo> {
return this.post(todo);
}
deleteTodo(todo: ITodo): Promise<ITodo> {
return this.delete(todo);
}
private post(todo: ITodo): Promise<ITodo> {
let headers = new Headers({
'Content-Type': 'application/json'
});
return this.http.post('api/todos', JSON.stringify(todo), { headers })
.toPromise()
.then(res => res.json().data)
.catch(this.handleError)
}
private delete(todo: ITodo): Promise<ITodo> {
let headers = new Headers({
'Content-Type': 'application/json'
});
let url = `api/todos/${todo.id}`;
return this.http.delete(url, { headers })
.toPromise()
.then(res => todo)
.catch(this.handleError)
}
private handleError(error: any): Promise<any> {
console.log('The error occured >>>', error);
return Promise.reject(error.message || error);
}
}
My main.ts code
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS, XHRBackend } from '@angular/http';
import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory- web-api';
import { TodoSeedData } from './shared/todo.data';
import {AppComponent} from './app.component';
bootstrap(AppComponent,[
HTTP_PROVIDERS,
{ provide: XHRBackend, useClass: InMemoryBackendService },
{ provide: SEED_DATA, useClass: TodoSeedData },
]);
一切都工作正常,没有错误,直到我需要 http。
发现类似的问题here https://stackoverflow.com/questions/37088713/angular-2-http-module-load-issue
但这对我不起作用。
Console.log shows error: Collection 'todos' not found.
估计是http的问题。
请帮忙。