Angular 2 Promise Error

I am trying to make a service that processes 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 is working fine, if I get a status code 400+in the response, the code goes into catchstare, if the code 200goes into state thenand returns a response.

But when I use it inside the component, it goes into state thenregardless of whether it works normally 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 that I am missing, I have to throw something at the service, so the code goes to the startup error, I get the status code 400+?

Thanks Daniel!

+4
source share
2

catch, catch, , . - :

  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));
+5

- , , 400+?

, catch .

catch, , addContact.

+2

Source: https://habr.com/ru/post/1676079/


All Articles