2
votes

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?
1
why you need promise ? can't use Observable - CharanRoot
If you really want to return a promise, then just use toPromise() on the observable returned by http.get. - user663031

1 Answers

1
votes
  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));
    });
}