Angular 4: demo of observable vs. promise

Following code is meant to show the same REST API being called via a Promise and an observable. It was tested on:

  • OS: Win32, ia 32, windows 7
  • @angular/cli: 1.4.5
  • node: 6.11.3
  • npm: 3.10.10

 

app.module.ts

@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule ],
providers: [ ApiService ],
bootstrap: [ AppComponent ]
})

 

app.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { IPostType } from './IPosts.object';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
_postsArray: IPostType[];
_postsArrayPromise: IPostType[];

constructor(private apiService:ApiService) {}
ngOnInit():void {
this.getPostsUsingObservable();
this.getPostsUsingPromises();
}

getPostsUsingObservable(): void {
this.apiService.getPostsByObservable()
.subscribe(
resultArray => this._postsArray = resultArray,
error => console.log("Error :: " + error)
);
}

getPostsUsingPromises():void{
this.apiService.getPostsByPromise()
.then(articlesItems => this._postsArrayPromise = articlesItems);
}
}

 

IPosts.object.ts

export interface IPostType {
userId: number;
id: number;
title: string;
body: string;
}

 

api.service.ts

import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import "rxjs/Rx";
import { IPostType } from './IPosts.object';
@Injectable()
export class ApiService {

private _postsURL = "https://jsonplaceholder.typicode.com/posts";

constructor(private http: Http) { }

getPosts(): Observable<IPostType[]> {
return this.http.get(this._postsURL)
.map((response: Response) => {
return <IPostType[]>response.json();
});
}

getPostsByPromise(): Promise<IPostType[]> {
return this.http.get(this._postsURL)
.toPromise()
.then((response: Response) => {
/*console.log("output during GET(promise)" + response.json()); */
return Promise.resolve(response.json());
})
}
}

Advertisements