Angular 2 http service tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is part 27 of Angela to to do job in this video we'll discuss how to call a speeder and PvP a service using the angular built-in HTTP service does this example demonstrates calling an asp.net web api service we can use the same approach to call any web service belt using any server-side technology along the way we'll also briefly discuss what observable pattern is all about and finally issuing cross-domain service calls this is the asp.net web api service we built in our previous video this web api service ladies data from this employees database table at the moment we have the employee's data hard-coded within our angular employee service as you can see right here now instead of hard-coding employee's data within the application like this we want this service to call the web api service the web api service in turn retrieves data from the database table so let's look at the steps involved for calling a server-side web api service using the angular built-in HTTP service this HTTP service is present in a different angular module and that module is HTTP module so the first step is to import this angular HTTP module from our root application module which is add module so within this file right here app dot module dot TS we have our root application module app module now here let's import the HTTP module let's include a required import statement and just like how we have included browser module and forms module as part of the input sorry let's also include the HTTP module so with this change we are now able to use the built in angular HTTP service to issue web service calls over HTTP here are the two changes which we just made our second step is to modify the angular employee service to issue a get request using the angular built-in HTTP service our employee service is present in this file employee dot service dot TS now the first step here is to odhh HT DB from Angela HTTP here is the HTTP service so we are going to make use of this service to issue web service calls over HTTP so we now need to inject as HTTP service into our service class for that we are going to make use of the constructor to create a constructor in typescript we use the constructor keyword let's create a private field for the class and I'm going to call it underscore HTTP and the type for this is HTTP remember this shorthand syntax that we discussed earlier in this video series basically this is going to create a private field for this class with name underscore HTTP it also create a constructor parameter with the same name and then it initializes the private field with the constructor parameter to reduce the amount of code that we have to write to do something so common typescript has provided us with this shorthand syntax we can now use this private field underscore HTTP to issue web service calls over HTTP now notice this employees service class has an injected dependency it has a dependency on this injected HTTP service so now this at injectable decorator is mandatory if we don't have a dependency on this HTTP service then we don't have an injected dependency in that case we may omit this at injectable decorator but angular recommends to always use this at injectable decorator on a service class for consistency and future proof next we can use this private field underscore HTTP to issue web service calls so we can now get rid of this hard-coded data this dot under screw HTTP dot get now look at the intelligence look at what this get method returns it returns an observable of response we'll discuss what an observable is in just about but let's first import ABS sir verbal from rxjs next let's specify the URL to which we want to issue the get request be known this is the URL of our asp.net Web API service that returns us the list of employee objects so let's specify this URL right here as part of this get method now again if we look at the intelligence of this method notice it returns observable of response observable of response is not that useful to us we know this URL returns an array of AI employee objects right so I'm going to change the return type to observable of AI employee like that now if you look at the return type of this get method it is observable of response and silicate data - diaper for get employees method we changed it to observable of AI employee array so we need to convert response to i employee array to do that transformation we are going to make use of an operator provided by rxjs and that operator is map operator so let's include the required import statement for importing the map operator from rxjs and then we are going to change the map operator to the get method like this and we are going to pass the response that does get method returns right look at the return type of this get method it is observable of response so let's pass this response to this map operator basically the argument for this map operator is an arrow function we are going to use that arrow function to transform the response to i employee array so let's specify first the parameter that you want to pass I'm going to call the parameter response again if you look at the return type the return type of diskette method is observable of response so first let's import this response from angular HTTP so along with HTTP let's also import response and the type for this parameter that we are passing to the arrow function said that to response because that's what this get method is giving us the get method is giving us absorb all of response that response we are passing to the map operator and this arrow function right here is going to convert this response to an array of PI employee objects first let's get the JSON out of the response and then let's use the type testing operator and then we want to type gasps the response to I employee array so the map operator right here taking in the response and transforming it to I employee array which satisfies observable of I employee the return type that we have specified for our get employees method so here is that same code which issues a get request to our removed web service and notice our service returns an observable so let's now understand what is in absorber and observable is an asynchronous pattern in this pattern we have an observable and an observer this observable emits data items or notifications over a period of time and the observers also called as subscribers can subscribe to the observable when subscribing the observers specifies a callback function and that callback function of the observer also called a subscriber is notified whenever this observable emits data items and within that function will write code to handle the data items emitted by the observer and as you can see from this diagram an observer can have multiple observers studies subscribers anybody who is interested in the data emitted by the observable can observe the absorber meaning subscribe to the observer when they subscribe they specify a callback function within that function we have code to handle the data emitted by the observable it's as simple as that so if we relate this to our example in allocate this employees service returns an observable so it becomes an SOPA and any component which needs this employee data is going to be the observer also call a subscriber and let's say for example with another application within our employee list component we need employees data so that is going to be the observer subscriber and that component is going to subscribe to the observer they turn by this service and when we are subscribing from our employee list component to this service we are going to specify a callback function and whenever this function returns an observable of AI employee objects the subscriber the observer in our case employee list component is going to consume that and we have a callback function there which is going to handle the data returned by this observer so our next step naturally is to subscribe to the absorb ultra turn by our employee service from employee list component so let's see how to subscribe to an observer now let's open our employee list component it is going to be this observer that is the subscriber notice within the ng on init method we are issuing a request to the employee service which returns the observer and if you look at the intelligence for the scat employees method notice it returns observable of I employee and forget this property it is PI employee array so you can't bind absorb of AI employee directly to this property like this because this service returns an observable we have to subscribe to the absorber and to subscribe to the observer we use the SUBSCRIBE method like that notice we are changing the SUBSCRIBE method to get employees method which returns an observer and remember when we subscribe to the absorber we also specify a callback function we specify that callback function as a parameter to the SUBSCRIBE method so we can specify that as a arrow function or a regular function I'm going to use an arrow function so this error function is going to receive employee data so I'm going to name that parameter employee data you can give it any meaningful name you want and what do we want to do with that employee data as in when the observer you know returns employee data I want to use that data to populate employees property so I simply say this dot employees equals employee data you know whatever data they call back function receives from the observable and we don't need this assignment here anymore because we are using the callback function which is notified when the observable emits an array of my employee objects this parameter is going to receive the data and we are using that to bind to employee's property so to subscribe to an observable we just need one line use the SUBSCRIBE method and then specify the callback function as a parameter to that subscribe method and that callback function receives data from the observer and within this callback function in our case we are binding it to employee's property at the moment we only specified one argument to the SUBSCRIBE method if you look at the SUBSCRIBE method it actually has three parameters so let's look at that from intelligence so if you look at the SUBSCRIBE method notice the third overloaded version it has got three callback methods that we can specify this first method is the method that is called when an observable emits an item and that's what we have specified at the moment right here the second method is called on error so as the name implies this method is notified when there is an error so this callback method is called when there is an error processing of a request and we have the third method this is called uncompleted this method is called when absorb elem it's the last item remember an observable emits data items sequence of items over a period of time in our case however the observable emits just one item that is an array of I employee objects but if you have an observable which emits data items that is a sequence of items or a period of time then and when the observable emits the last data item that's when this uncompleted method is called in our case it emits only one item that is an array of I employee objects that's when this on next method is called and because we don't have any other items the observable is emitting immediately following that it also cause uncompleted we haven't specified on error on completed as arguments to the SUBSCRIBE method in our upcoming videos we'll discuss how to handle errors using on error callback method so with all these changes in place let's on our application by pressing ctrl f5 notice the webpage doesn't display any data let's launch browser developer tools and investigate what's going on now if you look at this error right here look at what it says cannot read properly length of undefined and we have this error within this method get total employees count button or employee list component so let's look at that method so we have that method right here get total employees count and we have just one line between that method is trying to conclude the length of employees array and here with an NG on an EDD we are assigning this property with the data returned by the service so what's happening here is by the time the service has the opportunity to initialize this property we are trying to read length property of the employees object so that's why we get this error cannot read property length of undefined so what do we want to do we want to delay they call to this method get total employees count until this ng on a net had the opportunity to initialize this property and the baby do that is by using structural directive ng F and if you look at baby are calling this method you're calling this within our Employee List component HTML so here we have the employee count component we are binding get total employees count to all property the input property so we want to delay the initialization of this employee count component and to do that we can use our structure - ng F and we specify our employees property so basically we are saying you know until this property is not null or it is not undefined don't initialize this employee count component so let's save these changes and free load of webpage notice now we see a different error rate this carefully look at what it says xml httprequest cannot load this URL no access control allow origin header is present on the requested resource origin this URL is therefore not allowed access we get this error because our angular application and our baby a project they are present in two different projects this our angular project and this is our Web API project because they are present in two different projects they are hosted at two different port numbers so this is our Web API project look at the port number 3 1 3 2 4 and this is our angular application and look at the port number for this 1 3 3 9 7 2 because they are present across two different port numbers they violate the browser same origin policy and the browser blocks this request for security reasons so to make this work all we have to do is include a setting within web config file of our baby a service let me peace that setting within the web config file of our web api project so under system dot web server let's include the setting so let's look at what the settings is so basically we are including that header access control Paulo origin and I'm setting it to star and we basically want to set the headers to content type and methods - all the methods get post put etc now if you are not clear on what these settings are we discussed them in greedier and parts 14 and 15 of our web api tutorial in that tutorial we are so discuss the browser same-origin policy and cross-origin resource sharing please watch those two videos so I'm not going to go into great details here and when we said this access control other origin to star then that basically means any application can issue it cross-domain requests to this web api service but if you want to restrict to only you our application so if you want to allow only this angular application to issue a cross-domain requests then you can specify the port number at which this application is running that is the domain at which this application is running in our case our Anglet application domain is this one localhost colon three three nine seven two so we can specify that right here or you can also use star so basically now we are saying only allowed this angular application cross-domain requests to this web api service so let's save all these changes and reload our web page notice now this CD data as expected and the application also works as before while we are here let me also show you another thing let's free build our solution notice within the status bar you can see rebuild all succeeded now let's issue a request from our web page now this is a first request after we have rebuild solution and look at what the message says it is no employees to display but that's not true if you look at our database table we have got employees in there so this message right here is misleading we are actually waiting here for the service to load data because we have rebuilt the solution it's taking some time to jet compile it and we are actually waiting here to you know for the service to produce data so that message no employees to display is misleading while we are actually waiting for the employees to load so a much better message would have been loading employees please wide so let's see how to fix that with an Employee List component I'm going to include another and look at the message we have here loading data please wait and notice this ng F structural directive and D F not employees so basically if employees property is not true the meaning if it is null or undefined that means we are actually waiting for the service call to return with data and initialize this property so during that wait period we want this message to be displayed loading data please wait and when the service called returns with data this TR disappears and the employees data show up and look at this TR right here this displays this message no employees to display and when do we want this TR to show up when the employees property is true the meaning when it is initialized and when the length is zero meaning we don't have any employee objects within that array to display that means we really don't have employees that's when we want to display this message no employees to display so with all these changes let's give our solution another rebuild within the status bar you can see rebuilt all succeeded so let's reissue a request from the browser notice while we are waiting for the service to load data it displays this message loading data please wait so at this moment the service is busy being did compiled and when the service returns with data that's going to initialize this property employees and when that happens this TR disappears and the employees data show up we have still waiting for the service to return with data notice as in when the data is available that message disappeared and we have the employee's data displayed now let's truncate this employee's table and now we don't have any employees within our employees table so now let's reissue the request to the browser now we expect the message to be no employees to display there we go the application is working as expected thank you for listening and have a great day
Info
Channel: kudvenkat
Views: 197,585
Rating: undefined out of 5
Keywords: angular 2 no access-control-allow-origin header is present on the requested resource, angular 2 cross-origin request blocked, angular 2 cross origin request, angular 2 http service observable, angular 2 http service example, angular observables tutorial, rxjs observables angular 2, angular 2 http get example, angular 2 http get request, angular 2 rxjs observable, angular 2 call web api, angular2 call rest service, angular2 call rest api, angular 2 http with observables
Id: DETRfgZGuk8
Channel Id: undefined
Length: 22min 14sec (1334 seconds)
Published: Tue Aug 08 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.