server.service.ts
import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Server} from './server'; import {Observable} from 'rxjs/Observable'; import {catchError, map} from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ServerService { constructor(private http: HttpClient) { } putAppName(name: string) { const appName = {'AppName': name}; this.http.put('https://angularsamples.firebaseio.com/data.json', appName).subscribe(); } getAppName() { return this.http.get('https://angularsamples.firebaseio.com/data.json').pipe( map((value, index) => { return value['AppName']; }) ); } }
app.component.html
<div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <div> App Name : <input type="text" [(ngModel)]="appName"/> <button class="btn btn-default" (click)="onSaveAppName()">Save</button> <p>{{appNameServer | async }}</p> </div> </div> </div> </div>
app.component.ts
import {Component, OnInit} from '@angular/core'; import {ServerService} from './server.service'; import {Server} from './server'; import {catchError, map, retry} from 'rxjs/operators'; import {of} from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { appName = ''; appNameServer; ngOnInit(): void { this.appNameServer = this.server.getAppName(); } constructor(private server: ServerService) { } onSaveAppName() { this.server.putAppName(this.appName); } }