-2

I found there is angular2/http service available in angular2 but please share best practice with me from angular2 because in past with angular there were two ways with $http and $resource now you should understand what i mean .

If possible share snippet.

khajaamin
  • 856
  • 7
  • 18

3 Answers3

1

Imagine a typical RESTful service with two resources:

  • One regarding the list of contacts: /contacts/. You can get the list of contacts (GET method) or add one (POST method)
  • One for a particular contact: /contacts/contactid. You can get the contact details (GET method), update it (PUT or PATCH method) or delete it (DELETE method).

Here is the correspond service to do that:

@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());
  }
}

Don't forget to subscribe even if no payload is received. Otherwise, the request won't be sent.

You can handle error using the catch operator or within the subscribed error callback according to your needs.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
1

Assuming you have imported all required files for http if not then read out this answer

First of all you have to decorate your http service class with decorator i.r @Injectable() , and there are lot of way of using http but as i am using which method ,i am posting here :-

To make Post request sometimes we have to send autorization key also something else by appending with headers so we have to use headers like this :-

this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + key)

Than you can use request method as you required i.e Get, Post, Put, Delete.

here is simple example of Post request using http :-

PostRequest(url,data) { this.headers = new Headers(); this.headers.append("Content-Type", 'application/json'); this.headers.append("Authorization", '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() }]
            }
        });
}

working example for Get request :-

Working Example of Get request

see also :-

Community
  • 1
  • 1
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Sample implementation of service looks like below -

@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');
    }

}

See if this helps.

Sanket
  • 19,295
  • 10
  • 71
  • 82