2

This is the HTTP Service, makes a get request that fetches longArray.js;

import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/Rx'; @Injectable() export class HttpService { constructor( private http: Http ) {} getHttpReq(url: string): Promise<any> { return new Promise((resolve, reject) => { this.http.get('http://192.168.0.189/longArray.js') .map(response => response.json()) .subscribe( function(response) { console.log("Success Response "); resolve(response); }, function(error) { console.log("Error happened " + error); reject(error); }, function() { console.log("Subscription is completed "); } ); }); } } 

This is a method that returns a bool promise depending on if longArray.js was fetched by getHttpReq (in class HttpService) or not;

getLongArrayTryOrFail(): Promise<boolean> { return new Promise((resolve,reject) => { this.httpService.getHttpReq('') .then(response => resolve(true)) .catch(error => reject(false)) }); } 
  • Is this method of creating HTTP Service correct?
  • Basically getHttpReq (in class HttpService) Subscribes to an Observable & either resolves or rejects the promise depending on subscription's successful response or error. Am I correct?
2
  • why you need promise ? can't use Observable Commented Jun 20, 2017 at 4:00
  • 1
    If you really want to return a promise, then just use toPromise() on the observable returned by http.get. Commented Jun 20, 2017 at 4:45

1 Answer 1

1
  1. Is this method of creating HTTP Service correct?

No, generally you shouldn't be consider using Promise with Observable.

  1. Basically getHttpReq (in class HttpService) Subscribes to an Observable & either resolves or rejects the promise depending on subscription's successful response or error. Am I correct?

There isn't any problem with your Promise implementation, but I don't understand why you're running away from using Observable. It has everything what you're looking for + they are lazy. Below is Observable implementation of the same in few lines of code.

Code

export class HttpService { constructor( private http: Http ) {} getHttpReq(url: string): Observable<any> { return this.http.get('http://192.168.0.189/longArray.js') .map(response => response.json()); }); } } //consumption getLongArrayTryOrFail(): Observable<boolean> { return this.httpService.getHttpReq('') .map(response => true) .catch(error => Observable.throw(false)); }); } 
Sign up to request clarification or add additional context in comments.

2 Comments

What's the purpose of the switchMap here?
@torazaburo map should do the trick. thanks for heads up. :) If I would have switchMap then I need to explicitly return Observable from there.. correct??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.