Angular HTTP Client Quick Start Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Very timely for me. Thanks!

👍︎︎ 2 👤︎︎ u/jprest1969 📅︎︎ Oct 10 2017 🗫︎ replies
Captions
mastering the basics of angular's HTTP module well open up the door to interact with thousands of exciting web-based api's by the end of this lesson you'll have the basic tools you would need to do things like request weather data stock quotes nutrition facts as well as interact with major platforms like Facebook Twitter and Amazon Web Services the one thing these products all have in common is that they provide a restful api that you can consume from your angular app Before we jump into the code let's quickly look at what a restful api is and how communication works between the client and the server so here we have a client on the left and a server on the right rest is simply a way for these two parties to communicate in a standardized way when the client makes a request it's going to use a specific verb or method to interact with the server first we'll go ahead and make a get request this tells the server that we only want to retrieve data and we're not going to modify it in any way the server will respond with the status code as well as the data that was requested if it was a successful request it should be a 200 level response but if the request wasn't valid it should be a 400 or 500 level error response a 400 response generally means the client screwed something up and a 500 level response generally means there was an error on the server itself if we send a post request we're telling the server that we intend to create new data when you send a post request you also send that data payload with it which is the data you intend to save on the server after the server successfully saves it it should respond with a 201 success message this time saying that the resource was created in addition to getting post you also have other verbs such as put patch and delete they all work in a similar way just conveying a slightly different message for what you intend to do on the server and that's basically the gist of how rest works from a very high level now let's start retrieving data from a restful endpoint using angular for this lesson I'm going to be working from a stack blitz project this allows me to include a link in the description where you can run this code and fork it for yourself the first thing we're going to do is go into the app module and import the HTTP client module from angular common ever since angular 4.3 we've had a client module built into common so just make sure that's the one you're actually using from there we can go into the the app component and import the HTTP client which works just like an angular service its injectable so we can just add it right in the constructor then I'm going to define a root URL variable that represents the main HTTP endpoint that we're going to be using for this demo I'm using JSON placeholder which is just a mock API that we can send request to and receive responses from so we'll just go ahead and copy and paste the URL and then we'll do the rest of the work in angular so first I'm going to opt out of typescript static typing and we're going to make a get request to the API first I define a get post method and then I'll define the post variable by a coin HTTP GET and that's going to return an observable so we'll pass in the route URL and that should return in observable of the response from the API and the HTML the first thing I'll do is set up a button that will trigger the API call and then from there I'm going to use ng-if to loop over the observable and unwrap it with the async pipe then I print it as a JSON object but you could do anything you want here with the underlying data now if we load the actual app in stack blitz we should see the response from JSON placeholder so after clicking the post button we get a response of an array of different post objects for this first example I opted out of typescript but now I'm going to show you how to use your own interface and pass it down to the get method so we're exporting an interface called post and it's just going to have a couple of properties here for an ID user ID title and body now we can import it back in the app component and we'll also import the rxjs observable and then we'll apply these to the post variable so we're going to say our post variable is an observable that contains an array of post objects that adhere to the post interface the return value on HTTP GET is typed as an object so we need to change that to our post array so if we go ahead and run this code we get the exact same result but we have the benefit of strong typing in our code at this point so now I'll go ahead and opt back out of typescript show you how to send URL parameters with your requests it's really common to send a parameter with the request to limit it or filter it in some kind of way on the server with JSON placeholder we can filter posts by the user ID so this is how we would do it if we were going to hard-code the parameter we'd have a question mark followed by the parameter and equals some value this works fine but it's not a very maintainable way to go because if we have multiple parameters or if they get created dynamically it's going to be hard to hard-code them directly in a string what we can do instead is use angular's HTTP params class to build these parameters dynamically we do that by instantiating a new instance of the class and then we can call set or append on the parameter and the value that we want to set and then we passed that as an object as the second argument to our get request when we send this parameter JSON placeholder will only return the posts that have this matching user ID we can follow a very similar process for HTTP headers which is going to be a very common use case if you're using authentication in your app let's imagine that we want to send a request that can only be performed by that currently logged in user in that case we could hypothetically send a JSON web token with their authentication details in the header then the server could decode that token to validate that this user does have the right permission to make this request so just like before we pass the headers as the second argument in the get request so now I'm going to test this out by going to that network tab in chrome we can inspect the request in the headers tab and we can see here that it has the authorization token that we had defined in angular so now let's go ahead and send a post request where we actually modify data on the server so we'll create a new variable called new post and also create a new method to handle this operation post is almost identical to get the only difference is we send a body with the request that represents the data that we want to modify on the server so we'll go ahead and create some random post data here and then we'll send this object as the second argument to the post request so we call HTTP post to the same URL and pass it the data payload and the HTML will create another button that triggers that create post method the new post variable is just a single object observable so we can get that data by calling async and JSON then we can load the app and if we click create post you see we get back here the object itself with that new data that was created on the server one of the most powerful features about angular's HTTP client is that you can use any rxjs operator on it so let's say we want to map the post down to just the title we can just throw in the map operator and then map the post down to just its title so if we rerun the same method we get just the title back instead of the full object as you can imagine there's all kinds of clever things you can do with rxjs to handle multiple requests and map everything down to the exact data format that you want you can also use rxjs to handle errors so in this case we'll import the catch and retry operators and also the observable of operator then I'm going to make the post request on an endpoint that doesn't actually exist which is going to trigger an error response first I'm going to tell rxjs to retry the request three times if it fails and if it continues to fail we'll go ahead and catch it and we'll console.log it as well as return it back as an observable I'm doing this just to show you the response on the front end and we can do that by returning and observable of the error itself so if we try this out we can see we get four post requests here the original one plus the three retries and when it fails for good it console logs the error and displays the error object in the user facing front end so that covers the basic HTTP concepts that you need to know to get started using third-party API is an angular but there is one really cool tool I want to show you before the end of this video called swagger it's a framework for building an API is both server-side and client-side it allows you to define API code in a readable Yambol format and it can actually automatically generate a lot of your angular client-side code so you would define the details of your API here on the left and then it gives you a readable documented format of it on the right then if you go up to generate client and go to typescript angular 2 it will generate an entire angular app with the swagger API built into it you can download the generated code and then open it in your editor and you'll see you have a bunch of angular code here with the HTTP module but I should warn you this is the previous version of HTTP and angular so just keep that in mind many of the methods and concepts will be identical but you won't be able to use this code line for line in any case it should give you some good ideas and help you jump-start the process of building your own front-end API client that's it for angular HTTP if this video helped you please like and subscribe and if you want to go beyond the basics consider becoming a pro subscriber at angular firebase comm you'll get a free copy of my book as well as one on one project consulting thanks for watching and I'll see you next time [Music] [Applause]
Info
Channel: Fireship
Views: 148,159
Rating: 4.90766 out of 5
Keywords: angular, angular 4, angular 2, firebase, webdev, app development, typescript, javascript, lesson, tutorial, http, restful api, api, angular http, angular rest, angular http tutorial, api request angular, swagger api, angular 4.3 http
Id: _05v0mrNLh0
Channel Id: undefined
Length: 9min 56sec (596 seconds)
Published: Mon Oct 09 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.