Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m
Angular 3
  • Overview
  • Transcript

2.4 The Projects Service

Right now the projects that we are displaying to the user are just hard coded right into our projects component. However that's not a long term solution. What we want to do is have some way of getting a list of projects from our server. So in this lesson we are going to create a project service. In Angular a service is basically any set of functionality that we want to be available to multiple components. Basically it's just an easy way to wrap up some functionality. So inside of our app directory, let's create a projects service. And we'll call this projects.service.ts. Now of course a service is not a component, so there's no need to import the component decorator. But there is another decorator that we need and that is injectable. So let's import Injectable from angular/core. Now as I said Injectable is a decorator and it doesn't take any properties. So we'll just call Injectable and then we'll go ahead and export our class here which we're going to call ProjectsService. Injectable basically makes this class something that Angular can use as dependency injection. As we'll see a bit later on in this lesson, we use dependency injection to get an instance of this project service within a component that uses the project's service. An Angular cue uses dependency injection in this way so that it can easily inject mock services and things like that if you want to test your components. So let's go ahead and add some methods to our ProjectService here. First of all we're going to need the HTTP module that Angular has. This will allow us to make requests directly to the server. So let's go ahead and import Http, and we will also import the response class which we will need for some type checking. And both of these comes from angular/http. Now, we should also import the Http module into our app modules file. So, let's go ahead and do that before we forget. Up here in our native modules, I will import the HttpModule and then down here in our imports, let's go ahead and include the HttpModule. All right, that was quick and easy. And now that we've imported that in both the necessary places, we can go ahead and use dependency injection to inject this Http class into our ProjectService. So instead of doing something like new Http in here what we'll do is we'll create a constructor function here. And this constructor it will take as a property Http and will tell it it should be of the type Http. First of all, just to be clear, this first Http here is basically our own property name or our own parameter name. We could call this something like myajaxlink or something else like that I'll just keep it simple with Http. And basically what's gonna happen here is Angular will see this parameter when it's creating our ProjectService instance and it will match this Http class here to the HttpModule that we imported into our app module, and it will inject an instance of that into this constructor here. Now, what we could do in here, is say this.http = http and that way we will assign this parameter here into a property of our class so that we can use it in other methods. But typescript actually has some short cut syntax for that, what we can do is just give this a private keyword here. And this is the way we would create a private property on a class. For example we could do private name equals andrew or something like that to create a private property that would not be available from outside this class. But the shortcut here is that if we apply the keyword private directly inside a constructor, typescript will automatically assign this as a property. And now from within our other methods, we can use this .http. So let's create a function here called getProjects. This is going to be the method that we call to get our list of projects. Now with functions in typescript, we can still use the colon Type syntax. And in place of Type here, what we need to do is put in whatever value we expect to return from getProjects. And for getProjects we are going to return an Observable that wraps our type Project. So before we talk about what that is, let's import those two classes. So I'm going to go ahead and import Observable, and we will import that from our rxjs and let's also import the project from our Project model. So what is an Observable? Unfortunately there's no way I could give you a complete introduction to observables here but Angular too does depend quite a bit on observables and I will try and make them as simple as possible as we go through this. Basically, an observable is a wrapper similar to a promise or an array. Both promises, arrays, and observable have other items inside of them. In the case of an array, we have multiple items. In the case of a promise, we basically have some single value that we will get at some time in the future. With observables, it could be one value or it could be many values. One definition that's sometimes used is an asynchronous array. Basically, an observable is a stream of data that we may get more of at any time. And I think you'll see over the course of some lessons here how we can use observables to make getting and setting some of our data quite a bit easier. For now if you haven't seen observables before you can just think of it as a type of promise. So what will we return from this function? Well we can do this.http.get and let's get /api/projects and that rote will return our list of projects. And then what we can do is map the response here to a function that we're going to write called this.extractData. Okay, now the map function here, you can kind of think of as the then method on a promise. It's mapped just like on an array where basically on an array, you have the array as a container for some values. And then map will perform some operation on each one of the values inside that container and then return a new array with those new values. So basically, map allows you to perform some kind of action on the values inside a container. And the same thing is true with the then method in a promise. You can call then on a promise to call some function on the value inside of a promise. And then that returns a new promise with whatever new value you created inside that promise. Same thing with map here. We are gonna call extractData on the response that's inside this observable and what we will return from this is an observable that wraps a project. So up here let's create an extractData function and this is going to take a response and we will use our type checking here using the response class that we got from Angular Http. So what we'll just do is return res.json and this will just convert the Http response that returns to the actual JSON body. Now the value from extractData here will be returned inside of our getProjects call here and Angular will see that this matches are return type here because it will be an array of projects. And actually I've just realized that we made a mistake. This is an observable that doesn't just wrap a single project it wraps an array of projects. So we'll say project array and so when this res.json returns to getProjects here and we return Typescript will see that this is an observable object and it does wrap an array of objects that match our project type definition. And so everything will check out. So now that we have this getProjects function let's head over to our projects component and let's import it. So first of all, let's import the ProjectsService. Now because we want to inject a ProjectsService instance into this component, we'll need to tell Angular that it needs to provide an instance for this component. So let's add a provider's property to a component decorator here and we'll just tell it that it's going to need that ProjectsService inside of this component. So in here, let's add a constructor and we can use dependency injection in the same way that we did in our service. We will create a variable called service and this is going to be a ProjectsService object and so Angular will know to inject one of our ProjectsService instances into this class and then we'll give it the private key word here so that it sets that immediately as a property. With this in place we can go ahead and use it inside ngOnInit. So in here we can call this.service and the function that we created was called getProjects. So let's say this.service.getProjects and remember this returns an observable and the method that we want to call here is subscribe. And you can think of the subscribe method as if we were calling then on a promise that was returned, or if you think about this as an array, subscribe is like the for each method on an array. Where it's kind of like map and that it receives whatever is inside of the array or in this case the observable. However for each does not return a new array and subscribed does not return a new observable. So it's kind of like the end of the line. So subscribe is going to get our projects list as its parameter and so then here we can just save this.projects and of course this.projects refers to our array of projects here. This.projects will equal projects and that way we can assign that value and now that value should be available from within array. And if we come back to the browser to see our list of projects it looks like we are getting a 404 from /API/projects. That's kind of strange. Let me make sure our server is running. So if we go to local host 9876/API/Projects. Yep we can see the project data here. So we should get our list of projects. However the proxy server doesn't seem to be running. Let's go back and take a look at our servers here. If I quit the server and let me rerun the server. If we look at the output that we're getting here did not detect a bs-config.json or bs-config.js override file so it's using the defaults. Okay that's not what we want. If we head over to our terminal here we do have a bs-config file. Let's go look inside that. Everything looks okay. Did we forget to install the middleware proxy? Let's see npn install, we'll make sure we save that http-proxy-middleware. All right so we're sure that's installed now. Let's go ahead and restart the server and just make sure that that is working. Okay yeah and I just saw that output right there. You can see right here Proxy created: /api to our server, excellent. Okay so it looks like we forgot to install that package. And you know what this type thing is going to happen all the time when you're doing development. You're gonna forget small things and you'll have to backtrack and find the cause of a bug but once you do, as you can see we have success. We are successfully displaying the three projects that I put in the server and of course if we look at the Network tab here. Now let's refresh the page, then you can see that right at the bottom here, we have our request to /api/projects that our service is making and we have the response back. So we are successfully displaying our list of project titles. However we're gonna want to display a lot more than this to our user. So in the next lesson, we'll create some nice looking cards that will display more project information.

Back to the top