【发布时间】:2016-06-08 08:54:56
【问题描述】:
我发现 angular2 中提供了 angular2/http 服务,但请与我分享 angular2 的最佳实践,因为在过去使用 angular 时,$http 和 $resource 有两种方式,现在您应该明白我的意思了。
如果可能的话,分享sn-p。
【问题讨论】:
标签: angular
我发现 angular2 中提供了 angular2/http 服务,但请与我分享 angular2 的最佳实践,因为在过去使用 angular 时,$http 和 $resource 有两种方式,现在您应该明白我的意思了。
如果可能的话,分享sn-p。
【问题讨论】:
标签: angular
想象一个具有两种资源的典型 RESTful 服务:
/contacts/。您可以获取联系人列表(GET 方法)或添加一个(POST 方法)/contacts/contactid。您可以获取联系人详细信息(GET 方法)、更新它(PUT 或 PATCH 方法)或删除它(DELETE 方法)。这是执行此操作的相应服务:
@Injectable()
export class ContactService {
baseUrl:string = 'http://...';
constructor(private http:Http) {
}
getContacts() {
return this.http.get(baseUrl + '/contacts/')
.map(res => res.json());
}
addContacts(contact) {
var payload = JSON.stringify(contact);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get(baseUrl + '/contacts/', { headers })
.map(res => res.json());
}
getContact(contactId) {
return this.http.get(baseUrl + '/contacts/' + contactId)
.map(res => res.json());
}
updateContacts(contact) {
var payload = JSON.stringify(contact);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.put(baseUrl + '/contacts/' + contact.id, { headers })
.map(res => res.json());
}
deleteContact(contactId) {
return this.http.delete(baseUrl + '/contacts/' + contactId)
.map(res => res.json());
}
}
即使没有收到有效载荷,也不要忘记订阅。否则,请求将不会被发送。
您可以根据需要使用catch 运算符或在订阅的错误回调中处理错误。
【讨论】:
假设您已导入 http 所需的所有文件,如果没有,则读出此答案
首先你必须用装饰器 i.r @Injectable() 来装饰你的 http 服务类,并且有很多使用 http 的方法,但是当我使用哪种方法时,我在这里发布:-
为了发出 Post 请求,有时我们必须通过附加标头来发送自动密钥,所以我们必须使用这样的标头:-
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + key)
您可以根据需要使用请求方法,即获取、发布、放置、删除。
这里是使用 http 的 Post 请求的简单示例:-
PostRequest(网址,数据){ this.headers = new Headers(); this.headers.append("Content-Type", 'application/json'); this.headers.append("授权", 'Bearer' + localStorage.getItem('id_token'))
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: this.headers,
body: JSON.stringify(data)
})
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
return [{ status: res.status, json: res.json() }]
}
});
}
Get 请求的工作示例:-
Working Example of Get request
另见:-
【讨论】:
服务的示例实现如下所示 -
@Injectable()
export class WebApiService {
private _webApiUrl = 'http://localhost:3025/api/Employee';
constructor(private _http: Http) {
}
getEmployees(): Observable<{}> {
return this._http.get(this._webApiUrl)
.map((response: Response) => <any[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError)
;
}
getEmployee(id: number): Observable<IEmployees> {
return this.getEmployees()
.map((emp: IEmployees[]) => emp.find(p => p.ID_EMP === id));
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
看看这是否有帮助。
【讨论】: