我发现有angular2/HTTP在angular2提供服务,但请从angular2与我分享最佳做法,因为在过去的角度有两种方式可以用$ http和$资源现在你应该明白我的意思。我们如何在angularjs 2中使用其他webservices?
如果可能的份额片段。
我发现有angular2/HTTP在angular2提供服务,但请从angular2与我分享最佳做法,因为在过去的角度有两种方式可以用$ http和$资源现在你应该明白我的意思。我们如何在angularjs 2中使用其他webservices?
如果可能的份额片段。
服务的示例实现看起来像下面 -
@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');
}
}
看看这会有所帮助。
想象一下,一个典型的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,如果没有则读出这个答案
首先你装饰用装饰IR @Injectable()
你的HTTP服务类,以及有很多使用http的方式,但由于我使用的方法,我在这里发帖: -
要发布采购信息,有时我们不得不派autorization钥匙也未尝另外通过与头追加所以我们必须用头是这样的: -
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + key)
不是你需要的即获取您可以使用请求方法,POST,PUT,DELETE。
这里是使用HTTP POST请求的简单示例: -
PostRequest(URL,数据){ this.headers =新集管(); this.headers.append(“Content-Type”,'application/json'); this.headers.append(“Authorization”,'承载者'+ 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
还看到: -
的https: //angular.io/docs/ts/最新/引导/服务器communication.html – rinukkusu