4

i'm still learning observable in angular 2, and has not been able to figure out how to convert my code in angular 1 to angular 2.

function promiseFunc() {
  var deferred = $q.defer();      

  $http.post(url, something)
    .then(function (response) {
      if (response === 1) deferred.resolve(response.data);
      else deferred.reject();
    }).catch(function (e) {
      deferred.reject(e);
    });

  return deferred.promise;
}    

Can anyone tell me how i can convert this code with angular 2 observable?

EDIT:

And what if the http.post is optional?

function promiseFunc(param1) {
  var deferred = $q.defer();      

  if (param1 === 1) {
    deferred.resolve(1);
  } else {
    $http.post(url, something)
      .then(function (response) {
        if (response.x === 1) deferred.resolve(response);
        else deferred.reject();
      }).catch(function (e) {
        deferred.reject(e);
      });
  }

  return deferred.promise;
}

What i'm missing in observable is the ability to call resolve and reject. Can it be done in observable?

Reynaldi
  • 1,125
  • 2
  • 19
  • 41
  • The problem is that you're relying on [deferred antipattern](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern), which isn't inherent to Promises/A+ and can't be directly translated to observables (they wouldn't call it antipattern for nothing). – Estus Flask Nov 10 '16 at 07:05

1 Answers1

3
someMethod() {
  if(param === 1) {
    return Observable.of(1);
  } else {
    return this.http.post(url, something)
    .map(
      response => {
       let data = response.json();
       if(data === 1) {
         return 1;
       }
       throw 'some error';
      }
    );
  }
}

then use it like

this.someMethod().subscribe(
  data => console.log(data),
  error => console.log(error),
  () => console.log('completed')
);     
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567