我正在尝试创建一个处理联系人的 Angular 2 服务。这是目前我所做的。
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
状态;如果是200
状态码,它会进入then
状态并返回响应。但是当我在组件中使用它时,无论响应是否正常,它都会进入then
状态。addingContact() {
this.contactsService
.addContact(this.user)
.then(
(contactx) => { console.log('THEN = ' + JSON.stringify(contactx)); },
(err) => { console.log('CATCH = ' + JSON.stringify(err)); }
);
}
我有些疑惑,如果我收到一个400+
状态码,是否应该在服务上添加某些内容,以便代码转到错误起始点?
提前感谢您,丹尼尔!