Angular http get example using httpclient

Декораторы полей классов для директив и компонентов¶

Объявляет входное свойство, которое можно обновить с помощью привязки свойства (пример: ).
Объявляет выходное свойство, которое запускает события, на которые вы можете подписаться, с привязкой к событию (пример: ).
Связывает свойство элемента хоста (здесь класс CSS ) со свойством директивы / компонента ().
Подписывается на событие элемента хоста () с помощью метода директивы / компонента (), опционально передавая аргумент ().
Привязывает первый результат запроса содержимого компонента () к свойству () класса.
Связывает результаты запроса содержимого компонента () со свойством () класса.
Привязывает первый результат запроса представления компонента () к свойству () класса. Недоступно для директив.
Связывает результаты запроса представления компонента () со свойством () класса. Недоступно для директив.

HTTP Headers

You can also add HTTP Headers using the option as shown below. You can make use of the Http Interceptor to set the common headers.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

//HTTP Headers

getReposHeaders(userNamestring)Observable<repos>{

constparams=newHttpParams()

.set(‘sort’,»description»)

.set(‘page’,»2″);

constheaders=newHttpHeaders()

.set(‘Content-Type’,’application/json’)

returnthis.http.get<repos>(this.baseURL+’users/’+userName+’/repos’,{‘params’params,’headers’headers})

.pipe(

map((response)=>{

returnresponse;

}),

catchError((err,caught)=>{

console.error(err);

throwerr;

}

)

)

}

 

Syntax of AngularJS $http.post Method

Following is the syntax of using $http.post method in angularjs applications.

var app = angular.module(‘putserviceApp’, []);

app.controller(‘putserviceCtrl’, function ($scope, $http) {

// Simple Post request example:

var url = ‘posturl’, data = ‘parameters’,config=’contenttype’;

$http.post(url, data, config).then(function (response) {

// This function handles success

}, function (response) {

// this function handles error

});

});

If you observe syntax of angularjs $http.post method we have different properties like url, data, config and then success and error functions. We will learn each property in detail.

Property Description
url We need to send url of http server to perform required operations.
data We will use this property to send required parameters to requested url.
config By using this property we can change content-type.

In above syntax, we passed $http as argument to the controller. To use service in controller we need to pass $http as parameter.

The response object which we will get after execution of $http.post method has following properties

  1. config  — The configuration object is used to generate the request.
  2. data — It’s either string or an object.
  3. headers — We can get header information.
  4. status — We can get HTTP status code of the response.
  5. statusText — Get HTTP status text of the response.

We will see how to use $http.post service in angularjs with example.

Simple $http.post example

What we will do here is introduce you to a simple example of the usage of . The idea on the user’s point of view is to submit a string (which can be a name, number, or whatever you wish) through an input field and then have that information displayed. For that we only have to use the shorcut method and a function that makes the JSON data into a string. The code for the HTML part would go like below:

post.html

<body ng-app='myApp'>

<div ng-controller="myCtrl">

    <form ng-submit="sendPost()">
        <input ng-model="newName"/>
        <button type="submit">Send</button>
</form>

{{hello.name}}

</div>

</body>

As you see, we’ve used standard AngularJS syntax such as the one for the or . We’ve bound the information entered in the input field to the and then we have used the expression to display it. Let’s take a look at all the behind the scenes of this part:

post.js

angular.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
    $scope.hello = {name: "ERA"};
    $scope.newName = "";
    $scope.sendPost = function() {
        var data = $.param({
            json: JSON.stringify({
                name: $scope.newName
            })
        });
        $http.post("/echo/json/", data).success(function(data, status) {
            $scope.hello = data;
        })
    }
})

First, before any name is entered in the input field, you’ll have the default displayed, which we have saved at the variable. The initial information in the input field is just an empty string, and we’ve saved it into the , as you might have noticed in the HTML part of the code.

You might have also noticed that the would invoke a function named which is the one that “stringifies” the data entered in the input field and posts it using by replacing with that info.

What is worth noting in this code snippet is the syntax used for the shortcut, which is the one used with the earlier versions of Angular JS. Remember to use the standard method instead of if you’re using the latest versions.

Don’t forget to include any external parts necessary into your main document such as the AngularJS file (I did forget that once while learning Angular. Don’t laugh!) or jQuery. With that, you’re set to go!

Observable¶

обрабатывают любой поток данных: примитивные типы, инициированные пользователем события, ответы сервера на HTTP-запросы, синхронный и асинхронный код.

Именно благодаря всему перечисленному библиотека нашла широкое применение в Angular.

Принцип работы объектов RxJS Observable можно сравнить с push-уведомлениями.

Так, объект выступает в качестве поставщика данных, который имеет обработчики поставляемых данных. Обработчики выполняют роль пользователей, реагирующих на отправку поставщиком данных.

При создании Observable конструктор класса принимает функцию с набором callback-функций в качестве аргумента. В переданной функции описывается логика обработки и возвращения значений.

Объект, принимаемый функцией, реализует интерфейс с тремя методами:

  • — принимает значение, которое будет возвращено функции-обработчику;
  • — принимает значение, возвращаемое функции-обработчику ошибок;
  • — вызывается для уведомления «подписчиков» об окончании рассылки.

Для обработки поставляемых данных используется метод , который принимает три функции: , и — для каждого из методов объекта конструктора.

Создание и использование объекта типа .

Здесь принимаемый функцией объект сначала используется для передачи значений (метод ), а затем для оповещения всех подписчиков об окончании рассылки (метод ).

Принимаемая конструктором функция возвращает метод , который вызывается для «ручной» отмены подписки. Обычно используется для освобождения занятых ресурсов (удаление таймеров или обработчиков событий).

Создавать собственные объекты приходится не так уж часто, поскольку большинство потенциально необходимого функционала, где можно было бы это применить, реализовано самим Angular.

Для создания, обработки и преобразования возвращаемых данных в RxJS предусмотрены специальные функции, называемые операторами. Например, оператор используется для преобразования примитивных типов в объект :

Оператор — более краткая запись следующего кода:

Если необходимо, чтобы обработчик вместо всего массива сразу получал каждый его элемент в отдельности, используйте оператор .

Начиная с версии Angular 5, импорт всех RxJS операторов осуществляется точно также, как и других сущностей Angular.

Теперь рассмотрим пример преобразования данных с использованием оператора .

Здесь умножает каждое значение элемента массива на 2.

Все операторы преобразования данных объявляются в методе через запятую. Сам метод импортировать не надо и он должен быть вызван перед методом .

Полный список RxJS операторов, разделенных по категориям, можно изучить на .

Response Type

The  determines how the response is parsed. it can be one of the ,   or . The default behavior is to parse the response as JSON.

Strongly typed response

Instead of , we can also use a  as shown below

1 2 3 4 5 6 7 8

addPerson(personPerson)Observable<Person>{

constheaders={‘content-type»application/json’}

constbody=JSON.stringify(person);

console.log(body)

returnthis.http.post<Person>(this.baseURL+’people’,body,{‘headers’headers})

}

 

String as Response Type

The API may return a simple text rather than a JSON. Use  to ensure that the response is parsed as a string.

1 2 3 4 5 6 7 8

addPerson(personPerson)Observable<Person>{

constheaders={‘content-type»application/json’}

constbody=JSON.stringify(person);


returnthis.http.post<Person>(this.baseURL+’people’,body,{‘headers’headers,responsetype’text’})

}

 

ViewContainerRef¶

Контейнером для представлений может служить абсолютно любой DOM-элемент

Важно отметить, что вставка представлений происходит не внутрь контейнера, а сразу после него

Но лучше всего использовать как контейнер специальный Angular-элемент .

Как и другие абстракции, ссылка имеет привязку в DOM-дереве.

Для осуществления манипуляций с представлениями внутри контейнера, у экземпляра класса предусмотрен ряд методов:

  • — вставляет представление на позицию (если не указан, то вставка осуществляется в конец);
  • — удаляет все представления из контейнера;
  • — возвращает представление типа по заданному индексу;
  • — возвращает индекс переданного представления;
  • — удаляет представление по конкретному индексу, если индекс не передан — удаляет последнее представление;
  • — меняет индекс представления на .

observe

The POST method returns one of the following

  1. Complete 
  2.  of the response
  3. .

By default, it returns the .

Complete Response

The following code will return the complete  and not just the 

1 2 3 4 5 6 7 8

addPerson(personPerson)Observable<any>{

constheaders={‘content-type»application/json’}

constbody=JSON.stringify(person);

returnthis.http.post(this.baseURL+’people’,body,{‘headers’headers,observe’response’})

}  

events

You can also listen to progress events by using the . You can read about observe the response

1 2 3

returnthis.http.post(this.baseURL+’people’,body,{‘headers’headers,observe’response’,reportProgresstrue})

 

Get Syntax

The above code is a very simple example of the HTTP method. The complete syntax of the method is as shown below. It has second argument , where we can pass the HTTP headers, parameters, and other options to control how the method behaves.

1 2 3 4 5 6 7 8 9 10 11

get(urlstring,

options{

headers?HttpHeaders|{headerstringstring|string;};

params?HttpParams|{paramstringstring|string;};

observe?»body|events|response|»;

responseType»arraybuffer|json|blob|text»;

reportProgress?boolean;

withCredentials?boolean;}

)Observable<>

 

  • use this to send the HTTP Headers along with the request
  • set query strings / URL parameters
  • This option determines the return type.
  • The value of responseType determines how the response is parsed.
  • Whether this request should be made in a way that exposes progress events.
  • Whether this request should be sent with outgoing credentials (cookies).

Creating an Angular 10 Project

After creating the API server, we can now proceed to create our Angular project using Angular CLI 10. In your terminal, navigate to the folder and run the following command:

The CLI will ask you if you Would you like to add Angular routing? (y/N) Type y and Which stylesheet format would you like to use? (Use arrow keys) Choose CSS and type . Your project should start generating the necessary files and installing the dependencies.

Now that we have created the project, before making of HttpClient to send HTTP requests let’s first create the basic buildings of our demo application which are simply an that interfaces with the REST server and a bunch of components for making a CRUD interface that calls the methods of .

Let’s start with the . In your terminal, run:

The command will generate the (for tests) and files.

Adding Routing & Navigation

To be able to navigate between these components, we need to add them to the router configuration. Open the file and update it accordingly:

Example of AngularJS $http.post() Service

Following is the example of using angularjs $http.post service in application.

Live Preview

<!DOCTYPE html>

<html>

<head>

<title>

AngularJs $http.post() Service Response Example

</title>

<script src=»http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js»></script>

<script type=»text/javascript»>

var app = angular.module(‘postserviceApp’, []);

app.controller(‘postserviceCtrl’, function ($scope, $http) {

$scope.name = null;

$scope.age = null;

$scope.adress = null;

$scope.lblMsg = null;

$scope.postdata = function (name, age, adress) {

var data = {

name: name,

age: age,

adress: adress

};

//Call the services

$http.post(‘/api/users/post’, JSON.stringify(data)).then(function (response) {

if (response.data)

$scope.msg = «Post Data Submitted Successfully!»;

}, function (response) {

$scope.msg = «Service not Exists»;

$scope.statusval = response.status;

$scope.statustext = response.statusText;

$scope.headers = response.headers();

});


};

});

</script>

</head>

<body>

<div ng-app=»postserviceApp» ng-controller=»postserviceCtrl»>

<div>

Name : <input ng-model=»name» /><br/><br/>

Age : <input ng-model=»age» /><br/><br/>

Adress : <input ng-model=»adress» /><br/><br/>

<input type=»button» value=»Send» ng-click=»postdata(name, age, adress)» /> <br/><br/>

</div>

<p>Output Message : {{msg}}</p>

<p>StatusCode: {{statusval}}</p>

<p>Status: {{statustext}}</p>

<p>Response Headers: {{headers}}</p>

</div>

</body>

</html>

Now we will run and see the output of above angularjs $http.post method that would be like as shown following.

Top angular-httpclient Askers

All Time

231

Aiyoub Amini 4,51366 gold badges2121 silver badges3333 bronze badges

187

Frennetix 2,45944 gold badges1111 silver badges2222 bronze badges

148

joshrathke 5,99655 gold badges1717 silver badges3333 bronze badges

114

LastTribunal 4,55577 gold badges3030 silver badges5959 bronze badges

106

nutzt 1,73333 gold badges1212 silver badges2121 bronze badges

66

Stepan Suvorov 21.8k2222 gold badges8787 silver badges161161 bronze badges

49

mrpotocnik 80311 gold badge88 silver badges1515 bronze badges

49

Sai Ram Gupta 73522 gold badges66 silver badges2222 bronze badges

40

Jean Carlos 1,07322 gold badges1313 silver badges2323 bronze badges

40

Hongyang Du 44911 gold badge44 silver badges99 bronze badges

40

Stylishcoder 87811 gold badge77 silver badges1919 bronze badges

32

efarley 5,76177 gold badges3232 silver badges5454 bronze badges

29

Fel 2,30244 gold badges2424 silver badges5252 bronze badges

26

Ralf Schneider 36311 gold badge44 silver badges1010 bronze badges

25

Amy 38711 gold badge33 silver badges1010 bronze badges

24

Bruno Miguel 46522 gold badges66 silver badges1515 bronze badges

24

Chris 95811 gold badge77 silver badges2323 bronze badges

23

roverred 1,50944 gold badges2323 silver badges4141 bronze badges

22

Phil 4,73844 gold badges3131 silver badges5959 bronze badges

19

Mr.H. 42955 silver badges1212 bronze badges

Only non community-wiki questions and answers are included in these totals (updated daily)

Requesting JSON using HttpClient.get

{ 
    writerId: 11, writerName: 'Mahesh',
    books: 
} 
writerUrl = "/api/writer"; 
writerUrl = "/api/writer";
getWriterWithFavBooks(): Observable&ltany&gt {
      return this.http.get(this.writerUrl, {responseType: 'json'});
} 
getWriterWithFavBooks(): Observable&ltany&gt {
      return this.http.get(this.writerUrl);
} 
getWriterWithFavBooks() {
  this.writerService.getWriterWithFavBooks().subscribe(
      data =&gt { 
	      this.favBooks = data;
	  }
      );
} 
export interface Book {
   id: number;
   name: string;
   category: string;
   year: string;
}
export interface Writer {
   writerId: number;
   writerName: string;
   books: Book[];
} 
getFavoriteWriter(): Observable&ltWriter&gt {
       return this.http.get&ltWriter&gt(this.writerUrl, {responseType: 'json'});
} 
getFavoriteWriter() {
    this.writerService.getFavoriteWriter().subscribe(
       data =&gt { 
          this.favWriter = data;
	  console.log(this.favWriter.books);
	 }
       );	   
} 
&ltdiv *ngIf="favWriter"&gt
  Writer Id: &ltb&gt{{favWriter.writerId}}&lt/b&gt, Writer Name: &ltb&gt{{favWriter.writerName}}&lt/b&gt
  &ltul&gt
    &ltli *ngFor="let book of favWriter.books" &gt
      Id: {{book.id}}, Name: {{book.name}}, Category: {{book.category}}, Year: {{book.year}}
    &lt/li&gt
  &lt/ul&gt
&lt/div&gt 

HttpClient.post with Headers

import { HttpHeaders } from '@angular/common/http'; 
let httpHeaders = new HttpHeaders({
     'Content-Type' : 'application/json',
     'Cache-Control': 'no-cache'
}); 
let httpHeaders = new HttpHeaders()
     .set('Content-Type', 'application/json')
     .set('Cache-Control', 'no-cache'); 
let options = {
     headers: httpHeaders
}; 
this.http.post&ltArticle&gt(this.url, article, options); 
createArticle(article: Article): Observable&ltArticle&gt {
     let httpHeaders = new HttpHeaders({
	'Content-Type' : 'application/json',
	'Cache-Control': 'no-cache'
     });    
     let options = {
	headers: httpHeaders
     };        
     return this.http.post&ltArticle&gt(this.url, article, options);
} 

Where can we find the official advocate on reusing HttpClient?

I mean, if and doing so is important, such advocate is better documented in its own API documentation, rather than being hidden in lots of «Advanced Topics», «Performance (anti)pattern» or other blog posts out there. Otherwise how is a new learner supposed to know it before it is too late?

As of now (May 2018), the first search result when googling «c# httpclient» points to this API reference page on MSDN, which does not mention that intention at all. Well, lesson 1 here for newbie is, always click the «Other Versions» link right after the MSDN help page headline, you will probably find links to the «current version» there. In this HttpClient case, it will bring you to the latest document .

I suspect many developers who was new to this topic did not find the correct documentation page either, that’s why this knowledge is not widely spread, and people were surprised when they found it out later, possibly in a hard way.

observe

The GET method returns one of the following

  1. Complete
  2. of the response
  3. .

By default, it returns the as shown in our example app.

Complete Response

The following code will return the complete and not just the

1 2 3 4 5

getReposRawResponse(userNamestring)Observable<any>{

returnthis.http.get(this.baseURL+’users/’+userName+’/repos’,{observe’response’})

}  

The complete response is as follows.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

  {

«headers»{

«normalizedNames»{},

«lazyUpdate»null

},

«status»200,

«statusText»»OK»,

«url»»https://api.github.com/users/tektutorialshub/repos»,

«ok»true,

«type»4,

«body»

{

«id»102269857,

******************Removed forclarity*****

}

}  

events

You can also listen to progress events by using the . You can read about observe the response

1 2 3 4 5

getReposRawResponse(userNamestring)Observable<any>{

returnthis.http.get(this.baseURL+’users/’+userName+’/repos’,{observe’events’,reportProgresstrue})

}  

Shortcut Methods of $http

AngularJS provides us with a number of shortcut methods for the basic usage of the $http service. These shortcut methods would be:

  1. – generates Http GET request and retrieves server data if the request is successful.
  2. – generates Http POST request and retrieves server data if the request is successful.
  3. – generates Http PUT request and retrieves server data if the request is successful.
  4. – generates Http DELETE request and retrieves server data if the request is successful.
  5. – generates Http HEAD request and retrieves server data if the request is successful.
  6. – generates Http PATCH request and retrieves server data if the request is successful.
  7. – generates Http JSONP request and retrieves server data if the request is successful.

All of these methods send a request to the HTTP remote server and get data from them in response. We’ll explain each of them shortly and then focus on . After we finish with all the details of that one, you’ll know the drill about basically each of them.

There are two (very similar, if I might add) scenarios of how the syntax of these methods could go. The first one is valid for all the methods above except and . It would go like below:

syntax.js

$http.get('/yourURL', config).then(successCallback, errorCallback);

We’ve used as an example, but it’s the same for all of them. The method only takes one mandatory parameter as an argument, and that would be the URL of the resource to which you’re sending the request. In our case, that is .

However, you can also add a second argument which you’re not obligated to, which is the configuration object, used to describe the request and how it is to be handled in detail. After that you only have to invoke the callbacks in case of success or failure, which we’ve aptly named and . To do that, we’ve used the function, assuming that you’re using a version of Angular that is released later than v1.4.8 (or usually considered v1.5.0).

Let’s see now the syntax for the two remaining methods: and . The code would go like below:

syntax.js

$http.put('/yourURL', data, config).then(successCallback, errorCallback);

As you can see for yourself, there is basically no other difference except one added argument to the method. That would be and it’s an argument you’re obliged to pass on. Like we mentioned, it’s an object which would contain the response body transformed using the transform functions.

Send Cookies

You can send cookies with every request using the as shown below. You can make use of the Http Interceptor to set the for all requests.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

//With Credentials

getReposWithCookies(userNamestring)Observable<repos>{

constparams=newHttpParams()

.set(‘sort’,»description»)

.set(‘page’,»2″);

constheaders=newHttpHeaders()

.set(‘Content-Type’,’application/json’)

returnthis.http.get<repos>(this.baseURL+’users/’+userName+’/repos’,{‘params’params,’headers’headers,withCredentialstrue})

.pipe(

map((response)=>{

returnresponse;

}),

catchError((err,caught)=>{

console.error(err);

throwerr;

}

)

)

}

 

URL Parameters

The URL Parameters or Query strings can be added to the request easily using the HttpParams option. All you need to do is to create a new  class and add the parameters as shown below.

1 2 3 4 5 6 7 8 9 10 11 12 13

addPerson(personPerson)Observable<Person>{

constheaders={‘content-type»application/json’}

constparams=newHttpParams()

.set(‘para1’,»value1″)

.set(‘para2’,»value2″);

constbody=JSON.stringify(person);

returnthis.http.post<Person>(this.baseURL+’people’,body,{‘headers’headers,’params’params})

}

 

The above code sends the GET request to the URL

The following code also works.

1 2 3 4 5 6 7 8 9 10 11

addPerson(personPerson)Observable<Person>{

constheaders={‘content-type»application/json’}

constbody=JSON.stringify(person);

returnthis.http.post<Person>(this.baseURL+’people?para1=value1&para2=value2′,body,{‘headers’headers))


}

 

Do we have to put HttpClient into a static property, or even put it as a singleton?

Based on the understanding of the previous section, I think the answer here becomes clear: «not necessarily». It really depends on how you organize your code, as long as you reuse an HttpClient AND (ideally) dispose it eventually.

Hilariously, not even the example in the

does it strictly right. It defines a «GoodController» class, containing a static HttpClient property that will not be disposed; which disobeys what emphasizes: «need to call dispose … so app doesn’t leak resources».

And lastly, singleton is not without its own challenges.

— Quoted from this inspiring talk, «Global State and Singletons»

The full details

Let’s have a look in turn at each of the entities listed above.

1. , and are of type , come directly from the DOM and are available as global variables, i.e. you don’t have to import or inject them in any way.

These are all ways of getting at the same thing. and are literally the same thing ( can be referred to explicitly but it is also the implicit global ). and are essentially the same thing, see this SO answer for more details on this.

You can find the MDN documentation for here.

So if the DOM is all that you want, I would just use . Some people like to be explicit that they’re accessing the object and prefer to use . The field of has a confusing history and seems to be the least popular way to access a DOM instance.

2. Elsewhere, you can see people using the Angular dependency injection token like so:

Then you can access . Again, this is simply a DOM instance, so if this is what you want, why bother injecting it when you can access it directly as ? The and the globally available mentioned above are both of type and, in a browser context, they are the same thing. So the only reason you’d inject it is if you’re working in a non-browser context.

You can find the Angular documentation for here and the MDN documentation for here.

3. Finally three Angular entities — , and .

Confusingly, Angular has used the same name for their location type (i.e. ) as the type of etc. up above. The DOM is available globally and doesn’t need to be imported, the Angular needs to be imported from .

The Angular entities , and are layered on top of each other, a contains a and a in turn contains a . None of them directly exposes the contained entity, i.e. you can’t get to the via the API nor to the via the .

You’ll see many older examples directly accessing but as its documentation makes clear, this «class should not be used directly by an application developer.»

Conclusions

So we started with a confusing array of entities but in the end, it really just boils down to choosing between the DOM provided global object and the Angular provided object. Under certain circumstances, may also be of interest.

Creating an Example REST API Server for Our Angular 10 Application

In this tutorial, we don’t need to create a REST API instead we’ll use json-server which allows us to quickly create a fake RESTful server and expose fake API endpoints, from sample data in a JSON file.

What is REST

Before creating an fake REST API server, let’s first understand what is REST.

Wikipedia defines REST as:

In more simple words: REST is a set of HTTP endpoints that provide a CRUD (Create, Read, Update, and Delete) interface on some server resources.

Creating the REST API

First, you need to install json-server via npm by running the following command:

Next, you need to create a JSON file, which will act as a database for our server. First, create a folder for our full-stack project and navigate inside it:

Next, create a folder inside the folder and navigate to it:

Next, create a file:

Open the file and add the following data:

You can either add some items manually or better yet let’s use Faker.js to automatically generate massive amounts of realistic fake data in Node.js and the browser.

First, initialize an empty Node.js module in the server folder:

This will generate a file with default values:

Next, install from npm using the following command:

Now, create a file:

Open it and add the following code:

We first import faker, next we declare an object with one empty array for customers then we enter a for loop to create 300 fake entries using faker methods like for generating a random first name. . Finally we convert the database object to a string and log it to the terminal.

Next, add a script to to generate the database file:

You can then run this command to create your file and populate it:

Finally, run the API server by executing the following command:

You can now send HTTP requests to the server just like any typical REST server. Your RESTful server will be available from the address.

These are the API endpoints we’ll be able to use via this REST server and using the previous configuration:

  • for getting the customers,
  • for getting a single customer by id,
  • for creating a new customer,
  • for updating a customer by id,
  • for partially updating a customer by id,
  • for deleting a customer by id.

You can use and parameters to get paginated data. In the header you’ll get , , and links.

For example:

for getting the first page of data, for getting the first five customers of the first page of data.

Response Type

The determines how the response is parsed. it can be one of the , or . The default behavior is to parse the response as JSON.

Strongly typed response

Instead of , we can also use a as shown below

1 2 3 4 5

getReposTypedResponse(userNamestring)Observable<repos>{

returnthis.http.get<repos>(this.baseURL+’users/’+userName+’/repos’)

}

 

String as Response Type

The API may return a simple text rather than a JSON. Use to ensure that the response is parsed as a string.

1 2 3 4 5

getReposTypedResponse(userNamestring)Observable<repos>{

returnthis.http.get<repos>(this.baseURL+’users/’+userName+’/repos’,{responsetype’text’})

}

 

URL Parameters

The URL Parameters or Query strings can be added to the request easily using the HttpParams option. All you need to do is to create a new class and add the parameters as shown below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

//URL Parameter

getReposUrlParameter(userNamestring)Observable<repos>{

constparams=newHttpParams()

.set(‘sort’,»description»)

.set(‘page’,»2″);

returnthis.http.get<repos>(this.baseURL+’users/’+userName+’/repos’,{‘params’params})

.pipe(

map((response)=>{

returnresponse;

}),

catchError((err,caught)=>{

console.error(err);

throwerr;

}

)

)

}

 

The above code sends the GET request to the URL

The following code also works.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

getReposUrlParameter(userNamestring)Observable<repos>{

returnthis.http.get<repos>(this.baseURL+’users/’+userName+’/repos?sort=description&page=2′)

.pipe(

map((response)=>{

returnresponse;

}),

catchError((err,caught)=>{

console.error(err);

throwerr;

}

)

)

}

 


С этим читают