“Places2Go” and the MEAN Stack (III)

From the latest post, I show how to have an app with angular2 and routing, using angular-cli. In this post I will add the services, dependecy injection and directives also using angular-cli

Source Code

The Full Source Code is available on GitHub:


Let´s start

The app running and the project

App Running

Step 01: Add a Classe (Model)

Let´s add a class, also referenced as a model:

$ ng generate class services/user.model

we can see that is just a little that do the ng command for our class … let´s add all of the other stuff with the atom editor:

An we also began to use the directives, in this case *ngFor to iterate over the mock user array, the result is

we should add a message when the user array is empty and in this case, *ngIf with:

<tbody *ngIf="users.length">
<tr *ngFor="let user of users">
<th scope="row">{{ user.id }}</th>
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td>{{ user.userName }}</td>
<tbody *ngIf="!users.length">
<th scope="row" colspan="4">no user!</th>

Step 02: Add a Services (Model)

The first option is to generate the services with the angular-cli command:

$ ng generate service <path-to-service/name>--flat : "--flat false" to indicate if a dir is created--spec specifies if a spec (testing file) file is generated--module (-m) allows specification of the declaring module$ ng generate --help service 

Let´s use it to generate a data service, with the testing class ( — spec), and we don´t want “flat” componentes: we want dirs

Let´s generate a dir “services” with the services inside: “services/data”$ ng generate service services/data --flat true --spec trueor the same is: by default is flat and generate spec file$ ng generate service services/data 

Let´s add the wired code to insert data from the service to the front end:

And we have the same result, we get the data, but this time from the service:

We can see that we set the provider : [DataService] in the @ component module, this enable the dependence injection. We can se the provider in the @ngmodule with the same result.

I will finish the post at this point, the tag and source code is in GitHub:

Ok, that was all for this post, I have seen how to use services in Angular and some things with Dependency injection, also I was using a little of directives

The next one could be connect the front with the backend, getting the data from the mongo DB database. Of course, we don´t access to the database directly, but through and API Rest… that is the part IV, let´s see you soon.


A good video about angular2 similar to this post is from Jhon Papa at ngConf (https://www.youtube.com/watch?v=WAPQF_GA7Qg&t=143s)

#cloud . #mobile ~} Sharing IT while learning It! ... Opinions are for my own