我们如何在angularjs 2中使用rest Web服务?

我们如何在angularjs 2中使用rest Web服务?,angular,Angular,我发现angular2中有可用的angular2/http服务,但请与我分享angular2的最佳实践,因为过去angular2有两种使用$http和$resource的方法,现在您应该理解我的意思了 如果可能的话,分享这个片段 服务的示例实现如下所示- @Injectable() export class WebApiService { private _webApiUrl = 'http://localhost:3025/api/Employee'; co

我发现angular2中有可用的angular2/http服务,但请与我分享angular2的最佳实践,因为过去angular2有两种使用$http和$resource的方法,现在您应该理解我的意思了


如果可能的话,分享这个片段

服务的示例实现如下所示-

@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所需的所有文件,如果没有,请读取此答案

首先,您必须使用decorator i.r@Injectable来修饰您的http服务类,使用http的方法有很多,但由于我使用的是哪种方法,我在这里发布:-

为了发出Post请求,有时我们必须通过附加标题发送自动化密钥,因此我们必须使用如下标题:-

this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + key)
然后,您可以根据需要使用请求方法,即Get、Post、Put、Delete

下面是使用http的Post请求的简单示例:-

PostRequesturl、数据{ this.headers=新标题; this.headers.appendContent-Type“application/json”; this.headers.appendAuthorization,'Bearer'+localStorage.getItem'id\u 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请求的工作示例:-

另见:-