Difference between revisions of "Using Angular HttpClient"

From PeformIQ Upgrade
Jump to navigation Jump to search
(Created page with "=Links= * * =Examples= Some examples. ==GET== <pre> getUsers() { this.httpClient.get(this.url').subscribe((res: any[]) => { console.log(res); this....")
 
 
(7 intermediate revisions by the same user not shown)
Line 8: Line 8:


==GET==
==GET==
In the .ts
<pre>
import { HttpClient } from '@angular/common/http';
</pre>


<pre>
<pre>
Line 26: Line 32:
</pre>
</pre>


Get a list of markers - this.markers:
<pre>
  getMarkers() {
    const url = this.baseUrl + '/v1/xxx/xxxx/markers';
    // console.log('[getMarkers]                                  url |' + url + '|');
    this.httpClient.get(url).subscribe((markers: Marker[]) => {
        // console.log('[getMarkers]                        markers |');
        // console.log(markers);


        this.markers = markers;
    },
    error => { this.errorMessage = error as any; },
    () => {
      // console.log('[getMarkers]            COMPLETED => markers |' + this.markers + '|');
      // Complete
    });


  } // getMarkers
</pre>


==POST==
==POST==


<pre>
<pre>
  addUser(user: User) {
    console.log('[addUser]                                    GUID |', this.user.Id);
    this.httpClient.post(this.baseUrl + '/v1/xxx/users',
    {
      email: user.email,
      lastName: user.lastName,
      firstName: user.firstName
    })
    .subscribe(
      data  => {
        console.log('[addUser]                POST Request is successful |' + data + '|');
      },
      error  => {
        console.log('[addUser]                                      Error |' + error + '|');
      });
  } // addUser
</pre>
=PATCH=
<pre>
  update(xxx: Xxx) {
    this.httpClient.patch(this.baseUrl + '/v1/xxx/xxxx-xxxx/' + this.id,
    {
      Id : xxx.Id,
      Status: xxx.Status,
      XxxId: xxx.XxxId,
      NoXxx: xxx.NoXxx
    })
    .subscribe(
      data  => {
        console.log('[update]              PATCH Request is successful |' + data + '|');
        return data;
      },
      error  => {
        console.log('[update]                                    Error |' + error + '|');
        return  error;
      });
  } // update
</pre>
=API Usage Examples=
<pre>
  public createUser(user: User) {
    return this.httpClient.post(`${this.apiURL}/users/`, user);
  }
  public updateUser(user: User) {
    return this.httpClient.put(`${this.apiURL}/users/${user.Id}`, user);
  }
  public deleteUser(userid: string) {
    return this.httpClient.delete(`${this.apiURL}/users/${userid}`);
  }
  public getUserById(id: string) {
    return this.httpClient.get(`${this.apiURL}/users/${id}`);
  }
</pre>
=Notes=
To add multiples params or headers you can do something like the following:
<pre>
constructor(private httpClient: HttpClient) {}
const url = `${environment.BaseUrl}/api/route`;
let httpHeaders = new HttpHeaders().set('one', one);
httpHeaders = httpHeaders .append('two', two);
httpHeaders = httpHeaders .append('three', three);
let urlParams = new HttpParams().set('one', one);
urlParams = urlParams .append('two', two);
urlParams = urlParams .append('param3', value3);


return this.httpClient.get<any[]>(url, { headers: httpHeaders, params: urlParams })
</pre>
</pre>


[[Category:Angular]]
[[Category:Angular]]

Latest revision as of 13:32, 24 October 2019

Links

Examples

Some examples.

GET

In the .ts

import { HttpClient } from '@angular/common/http';
  getUsers() {
    this.httpClient.get(this.url').subscribe((res: any[]) => {
        console.log(res);
        this.users = res;
    },
    error => { this.errorMessage = error as any; },
    () => {
      // Complete - update a datatable
      this.changeDetectorRef.detectChanges();
      const table: any = $('#UsersTable');
      this.dataTable = table.DataTable(this.dtOptions);
    });

  } // getUsers

Get a list of markers - this.markers:


  getMarkers() {

    const url = this.baseUrl + '/v1/xxx/xxxx/markers';

    // console.log('[getMarkers]                                  url |' + url + '|');

    this.httpClient.get(url).subscribe((markers: Marker[]) => {

        // console.log('[getMarkers]                        markers |');
        // console.log(markers);

        this.markers = markers;
    },
    error => { this.errorMessage = error as any; },
    () => {
      // console.log('[getMarkers]            COMPLETED => markers |' + this.markers + '|');
      // Complete
    });

  } // getMarkers

POST

  addUser(user: User) {

    console.log('[addUser]                                    GUID |', this.user.Id);

    this.httpClient.post(this.baseUrl + '/v1/xxx/users',
    {
      email: user.email,
      lastName: user.lastName,
      firstName: user.firstName
    })
    .subscribe(
      data  => {
        console.log('[addUser]                 POST Request is successful |' + data + '|');
      },
      error  => {
        console.log('[addUser]                                      Error |' + error + '|');
      });

  } // addUser

PATCH

  update(xxx: Xxx) {

    this.httpClient.patch(this.baseUrl + '/v1/xxx/xxxx-xxxx/' + this.id,
    {
      Id : xxx.Id,
      Status: xxx.Status,
      XxxId: xxx.XxxId,
      NoXxx: xxx.NoXxx
    })
    .subscribe(
      data  => {
        console.log('[update]              PATCH Request is successful |' + data + '|');
        return data;
      },
      error  => {
        console.log('[update]                                    Error |' + error + '|');
        return  error;
      });

  } // update

API Usage Examples


  public createUser(user: User) {
    return this.httpClient.post(`${this.apiURL}/users/`, user);
  }

  public updateUser(user: User) {
    return this.httpClient.put(`${this.apiURL}/users/${user.Id}`, user);
  }

  public deleteUser(userid: string) {
    return this.httpClient.delete(`${this.apiURL}/users/${userid}`);
  }

  public getUserById(id: string) {
    return this.httpClient.get(`${this.apiURL}/users/${id}`);
  }

Notes

To add multiples params or headers you can do something like the following:

constructor(private httpClient: HttpClient) {}

const url = `${environment.BaseUrl}/api/route`;

let httpHeaders = new HttpHeaders().set('one', one);

httpHeaders = httpHeaders .append('two', two); 
httpHeaders = httpHeaders .append('three', three);

let urlParams = new HttpParams().set('one', one);

urlParams = urlParams .append('two', two);
urlParams = urlParams .append('param3', value3);

return this.httpClient.get<any[]>(url, { headers: httpHeaders, params: urlParams })