Angular 2 Promise抛出错误 [英] Angular 2 Promise throw error
问题描述
我正在尝试创建一个处理Angular 2中的联系人的服务。这是我到目前为止所做的。
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());
}
}
现在服务工作正常,如果我得到 400 +
响应上的状态代码,代码转到 catch
stare,如果它是 200
代码转到然后
状态并返回响应。
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)); }
);
}
我有什么遗漏,如果我在服务上扔东西,代码转到错误开始,我得到 400 +
状态代码?
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 ?
提前谢谢你,Daniel !
Thank you in advance, Daniel!
推荐答案
你吞下catch中的错误,你仍然可以有一个catch子句来转换错误,但你需要返回被拒绝的承诺。类似的东西:
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));
这篇关于Angular 2 Promise抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!