Closed nasihere closed 8 years ago
import {Http} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {Observer} from 'rxjs/Observer'; import 'rxjs/add/operator/share'; import 'rxjs/add/operator/startWith';
export interface Todo { id: number; createdAt: number; value: string; }
export class TodosService { todos$: Observable<Todo[]>; private _todosObserver: Observer<Todo[]>; private _dataStore: { todos: Todo[]; };
constructor(private _http: Http) {
this._dataStore = { todos: [] };
this.todos$ = new Observable(observer => this._todosObserver = observer)
.startWith(this._dataStore.todos)
.share();
}
loadTodos() {
this._http.get('/api/todos').map(response => response.json()).subscribe(data => {
this._dataStore.todos = data;
this._todosObserver.next(this._dataStore.todos);
}, error => console.log('Could not load todos.'));
}
createTodo(todo: Todo) {
this._http.post('/api/todos', todo)
.map(response => response.json()).subscribe(data => {
this._dataStore.todos.push(data);
this._todosObserver.next(this._dataStore.todos);
}, error => console.log('Could not create todo.'));
}
updateTodo(todo: Todo) {
this._http.put(`/api/todos/${todo.id}`, todo)
.map(response => response.json()).subscribe(data => {
this._dataStore.todos.forEach((todo, i) => {
if (todo.id === data.id) { this._dataStore.todos[i] = data; }
});
this._todosObserver.next(this._dataStore.todos);
}, error => console.log('Could not update todo.'));
}
deleteTodo(todoId: number) {
this._http.delete(`/api/todos/${todoId}`).subscribe(response => {
this._dataStore.todos.forEach((t, index) => {
if (t.id === todo.id) { this._dataStore.todos.splice(index, 1); }
});
this._todosObserver.next(this._dataStore.todos);
}, error => console.log('Could not delete todo.'));
}
}
This pattern can ensure data is coming from one place in our application and that every component receives the latest version of that data through our data streams. Our component logic simple by just subscribing to public data streams on our data services. A working demo of a Observable data service can be found at this plnkr.co This service conforms to a REST based backend but could easily translate to a socket based service like Firebase without having to change any components.
To set up loading extra operators for the Observable included in Angular 2 core check out this GitHub Doc. To get more in depth review of Observables check out Rob Wormald’s intro to Observables or Ben Lesh’s RxJS In-Depth.
Hi Uttam,
Can you please call any dummy api call through Services and show that data json preview on view..
Test application that will give you help in mapping and calling api.
Thanks Nasir