<!DOCTYPE html>
<html>
<head>
<title>Angular 2+ Observable Data Services</title>
<script src="https://unpkg.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.8.4?main=browser"></script>
<script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
<style>
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
</style>
</head>
<body>
<todo-app>Loading...</todo-app>
</body>
</html>
A plunker demonstration Observable Data Services in Angular 2
https://coryrylan.com/blog/angular-2-observable-data-services
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';
import { TodoComponent } from 'app/todo.component';
import { TodoService } from 'app/todo.service';
@Component({
selector: 'todo-app',
template: `
<p>Only implimented a simple post and delete</p>
<h3>Component 1</h3>
<todo-component></todo-component>
<br /><br />
<h3>Component 2</h3>
<todo-component></todo-component>
`
})
export class AppComponent {
constructor() { }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { TodoComponent } from './todo.component';
import { TodoService } from './todo.service';
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule
],
declarations: [
TodoComponent,
AppComponent
],
providers: [ TodoService ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
import { Component } from '@angular/core';
import { FormBuilder, Validators} from '@angular/forms';
import { map } from 'rxjs/operators';
import { TodoService } from 'app/todo.service';
@Component({
selector: 'todo-component',
template: `
<div>
<form [formGroup]="todoForm" (submit)="onSubmit()">
<button>Add Item</button><br />
</form>
<p>
{{singleTodo$ | async | json}}
</p>
<div *ngFor="let todo of todos | async">
{{ todo.value }} <button (click)="deleteTodo(todo.id)">x</button>
</div>
</div>
`
})
export class TodoComponent {
todos: Observable<Todo[]>;
singleTodo$: Observable<Todo>;
constructor(
private todoService: TodoService,
private formBuilder: FormBuilder) {
this.todoForm = this.formBuilder.group({
'todo': ['', Validators.required]
});
}
ngOnInit() {
this.todos = this.todoService.todos;
this.singleTodo$ = this.todoService.todos.pipe(
map(todos => todos.find(item => item.id === '1'))
);
this.todoService.loadAll();
this.todoService.load('1');
}
onSubmit() {
this.todoService.create({ value: this.todoForm.controls.todo.value });
}
deleteTodo(todoId: number) {
this.todoService.remove(todoId);
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
export interface Todo {
id: number | string;
createdAt: number;
value: string;
}
@Injectable()
export class TodoService {
todos: Observable<Todo[]>
private _todos: BehaviorSubject<Todo[]>;
private baseUrl: string;
private dataStore: {
todos: Todo[]
};
constructor(private http: HttpClient) {
this.baseUrl = 'https://56e05c3213da80110013eba3.mockapi.io/api';
this.dataStore = { todos: [] };
this._todos = <BehaviorSubject<Todo[]>>new BehaviorSubject([]);
this.todos = this._todos.asObservable();
}
loadAll() {
this.http.get(`${this.baseUrl}/todos`).subscribe(data => {
this.dataStore.todos = data;
this._todos.next(Object.assign({}, this.dataStore).todos);
}, error => console.log('Could not load todos.'));
}
load(id: number | string) {
this.http.get(`${this.baseUrl}/todos/${id}`).subscribe(data => {
let notFound = true;
this.dataStore.todos.forEach((item, index) => {
if (item.id === data.id) {
this.dataStore.todos[index] = data;
notFound = false;
}
});
if (notFound) {
this.dataStore.todos.push(data);
}
this._todos.next(Object.assign({}, this.dataStore).todos);
}, error => console.log('Could not load todo.'));
}
create(todo: Todo) {
this.http.post(`${this.baseUrl}/todos`, JSON.stringify(todo)).subscribe(data => {
this.dataStore.todos.push(data);
this._todos.next(Object.assign({}, this.dataStore).todos);
}, error => console.log('Could not create todo.'));
}
update(todo: Todo) {
this.http.put(`${this.baseUrl}/todos/${todo.id}`, JSON.stringify(todo)).subscribe(data => {
this.dataStore.todos.forEach((t, i) => {
if (t.id === data.id) { this.dataStore.todos[i] = data; }
});
this._todos.next(Object.assign({}, this.dataStore).todos);
}, error => console.log('Could not update todo.'));
}
remove(todoId: number) {
this.http.delete(`${this.baseUrl}/todos/${todoId}`).subscribe(response => {
this.dataStore.todos.forEach((t, i) => {
if (t.id === todoId) { this.dataStore.todos.splice(i, 1); }
});
this._todos.next(Object.assign({}, this.dataStore).todos);
}, error => console.log('Could not delete todo.'));
}
}
/**
* WEB ANGULAR VERSION
* (based on systemjs.config.js in angular.io)
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'ts',
typescriptOptions: {
// Copy of compiler options in standard tsconfig.json
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
// paths serve as alias
'npm:': 'https://unpkg.com/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs@5.5.2',
'rxjs/operators': 'npm:rxjs@5.5.2/operators/index.js',
'tslib': 'npm:tslib/tslib.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api@0.4/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.4.2/lib/typescript.js',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
if (load.source.indexOf('moduleId') != -1) return load;
var url = document.createElement('a');
url.href = load.address;
var basePathParts = url.pathname.split('/');
basePathParts.pop();
var basePath = basePathParts.join('/');
var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;
if (!baseHref.startsWith('/base/')) { // it is not karma
basePath = basePath.replace(baseHref, '');
}
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
var resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return 'templateUrl: "' + resolvedUrl + '"';
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push('"' + basePath + match[2].substr(1) + '"');
} else {
urls.push('"' + match[2] + '"');
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};