Angular 2 Promise throw error

Pacuraru Daniel picture Pacuraru Daniel · May 1, 2017 · Viewed 10k times · Source

I am trying to make a service that handles contacts in Angular 2. This is what i got so far.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class ContactsService {

  constructor(private http: Http) { }

  addContact(contact): Promise<any> {
    return this.http
      .post('http://localhost:8000/contacts', contact)
      .toPromise()
      .then(response => response.json())
      .catch(error => error.json());
  }
}

Now the service works fine, if i get a 400+ status code on the response, the code goes to the catch stare, if it's 200 code it goes to then state and returns the response.

But when i use it inside a component, it goes to then state no matter if the respone is ok or not.

addingContact() {
  this.contactsService
    .addContact(this.user)
    .then(
      (contactx) => { console.log('THEN = ' + JSON.stringify(contactx)); },
      (err) => { console.log('CATCH = ' + JSON.stringify(err)); }
    );
}

Is there something i'm missing, should i throw something on the service so the code goes to the error start incase i get a 400+ status code ?

Thank you in advance, Daniel!

Answer

Julia Passynkova picture Julia Passynkova · May 1, 2017

You are swallow the error in catch, you can still have a catch clause to transform the error but you need to return a rejected Promise from it. Something like that:

  let httpPromiseMock  = new Promise((resolve, reject)=> {
    reject('400 error');
  });

 httpPromiseMock
 .then(x=> {console.log(x); return x*2;})
 .catch(x=> Promise.reject(`my error is ${x}`))
 .then(x=>console.log('good',x), 
    err=>console.log('bad', err));