Category Archives: Angular2

[EN] How to upgrade Angular 2 project to Angular 4

About a month ago Angular 4 has been released. You may want to ask what about version 3? Well, there’s no Angular 3. We have Angular 4, but I have started to learn Angular 2 and now what? Should I start to learn Angular 4 and forget about version 2? The answer is no. The newest version is backwards compatible with 2.x.x version. It’s just an evolution rather than revolution.

What’s new?
– applications are smaller and faster – the size of the generated code was reduced by around 60 %
– improved *ngIf and *ngFor
– angular universal – project that allows devs to run Angular on a server
– TypeScript 2.1 and 2.2 compatibility
– source maps for templates – when there is an error in a template, source maps are generated
More will come soon with v 4.1.

If Angular 4 has been released, why not to use it in our new project? Let’s see if it is easy to upgrade Angular 2 project to Angular 4.
Open command line tool, go to app folder and type commands as below, then wait a little.

1

After this we can check version of angular in our app by command

As you see here it is, Hello Angular 4.0.3 🙂

2

So far it’s good, we will see for some time how it works 😉

[EN] Calling ASP.NET Core WebApi from angular app

In the last post I showed how to create service in Angular, now it’s time to try call ASP.NET Core webApi from it.
I created Login controller in my ASP.NET Core WebApi project which contains SignIn method. I want to execute it. I don’t have completed implementation so far, I want only to test if it works. As you see it is HttpPost method and it returns message with current date and status – true.

SignIn method gets UserDto as parameter and it’s important to add [FromBody] attribute, if we want to deserialize json object properly. Let’s start our webApi and try to call it from angular app. It will not work if you didn’t configure WebApi properly to talk with other app. You will see HTTP 415 unsupported media type error everytime you call api. It took me a while to figure it out why it didn’t work, but finally I have found a solution.

Asp.Net Core WebApi configuration

To be able to call our API with success, there is small change in the configuration needed. In Startup class we need to modify a little bit Configure method. Here is default Configure method in ASP.NET Core project

The solution is to configure CORS. There is only one line of code needed. It has to be added before calling UseMvc method.

What is CORS?

It is Cross Origin Resource Sharing. It allows web page to make requests to another domain. We need to enable CORS, because if we have two applications in this case:
– http://localhost:63698/  – backend
– http://localhost:4200/ – frontend
These are two different ports and request doesn’t work correctly without using CORS.
It can be dangerous of course, because we can allow to make requests from another malicious site, but we can specify to use CORS only from the specific origin, from our site, e.g. http://localhost:4200/. In addition CORS builder has a fluent api, so we can add chain of methods, e.g. AllowAnyHeader() or AllowAnyMethod() or we can specify accepted headers. Let’s try to test our app. Here’s my login form. I typed login data and I clicked Login. Let’s see what is in console output.

1 2Yeah it works! This time I used dev console built in Chrome to check result of my request, but there are few other alternatives I want to share with you. For sure there will be a lot of cases when you want to trace your requests in detail during project development. I can recommend you two tools that I use. The first one is Fiddler from Telerik and the second one is Postman. These tools allows you to create requests and inspect them. Let’s take a quick look on Fiddler.

4

It is desktop application where you can for example use filters to inspect only specific addresses, compose requests and even more.
Postman is desktop application too, but not only. It is also available as extension for Chrome browser. Postman doesn’t scan your network communication. It only allows to create requests and see results, but it is very nice. It allows to save created requests in files.

5

It is good to know these tools exist, because sooner or later you will find them necessary for daily work.

[EN] Creating component and service in Angular2

Two posts ago I wrote about Angular2 application and I showed how to add new component and service. This time I want to show you how to implement a service in Angular2 and call webApi from it.

I decided to create login service in angular app which calls SignIn method from webApi (request via http post method).

Ok, let’s start. I have login.component and login.service in my angular app. First we need to make sure if login service is imported in login.module.ts and if it is added to providers list.

Next let’s implement the service.

First we need to import few things. You can ignore app/constants as you can see in my code, it’s just simple typescript class that contains constants. In the constructor we need to create http variable which will be used later.
SignIn function takes two parameters: username and password and returns boolean value. Then we have to construct http request that will be send to webApi. It’s very important to add headers that informs request contains json content, because webApi only accepts jsons. After http.post method there’s another method – map, which transforms the result to whatever we want.

Next is time to implement some code in login.component class. Let’s start from imports, don’t forget to import our service.

I have few variables in my login component, like username, password and 3 others that indicate an error. You can skip it, it’s not needed to achieve our goal from this post. I use it only to check if username and password are valid and show an error message in case they are not valid.

Let’s focus on onLogin() method. After few validations signIn method from login service is called with username and password which are passed as arguments. Subscribe method allows to define operation that we want to execute when result will come. I want to save username in localstorage and navigate to different component – welcome component.

What about login.component.html? It depends from you how you want to design it. There are a lot of samples in bootstrap 😉 Here is mine.

1

Basically you need to create a form.

and add ngSubmit directive that enables binding expressions to onsubmit events. We have onLogin method in login component that will handle it. We need also to bind input controls to our model

It will bind value from this control to _username variable in component class. I have also method binds to keyup event, but it’s only for validating input data. onKeyUp method in the component is responsible for it.

It looks we have all. Our service in Angular2 is ready. Now it’s time to start app and try to call webApi, but we will take a look at it in the next post.

[EN] How to debug angular app in VS Code and Chrome

I have started to develop frontend side of my pet project and yesterday I worked on login service and I had to debug it. I use Visual Studio Code to write app in angular2 and typescript and I thought why not to use VS Code for debugging? Ok, but not so fast. Few steps are required to achieve it.

In VS code open cmd palette with key combination Ctrl+Shift+P and type:

Then type Debugger for Chrome in extensions manager and install it.

1

After installation restart VS code.

Next go to Debugger or press Ctrl+Shift+D and click on the gear icon to create launch.json file.

2

By default it looks like this:

but to be able to debug angular app you need to modify it. My launch.json file looks like this:

Url is default url where angular app is located,  port: 9222 is the port used by Chrome browser.

In this config file there are two configs, one of these is for launching chrome with attached debugger and the second one is for attaching existing chrome instance. Let’s try to launch new chrome window. Click on green start icon.

3

Now you can just put a breakpoint in VS Code, wherever you want and you can debug your angular app 😉

[EN] Angular2 – project structure, changing css to sass, using CLI

Angular2 project structure

Few posts ago I showed how to create new Angular2 project using Angular CLI. Let’s take a look at the project structure. Here we have app folder which contains few items.

post7

Look at the diagram below to better understand this structure.

2

By default we have AppModule and AppComponent which is inside AppModule. This is how Angular2 project structure looks. We can have more components in one module and more modules with components of course.

34

Take a look into code. This is app.module class. It contains few core imports that come from angular library itself. There is also import of app.component class that has to be loaded. Beside it this class is empty for now.

Look at the app.component class. It imports angular/core only, but it has another interesting thing inside component. There is selector ‚app-root’ which will be used in index.html to display component interior, templateUrl which is link to html file with view for this component, styleUrls which is link to css file for our view. Inside class AppComponent we have title – ‚app works!’ which is visible when you run application.

Changing css to sass

Ok, we have css, but what if I want to have sass – css with super powers 😀 Sass is CSS pre-processor and allows you use variables, nested rules and more. It allows to create stylesheets faster. To change css to sass, first we need to download sass with npm

then set default extensions in our project

then we need to change styles from .css to .sass in .angular-cli.json file

and rename file from app.component.css to app.component.sass and rename another file from styles.css to styles.sass. In addition there’s one modification needed in app.component.ts file. StyleUrls should refer to sass file, not css file.

ok project supports sass files now.
Let’s implement something in our project. As I mentiond before about modules and components, every module should be created for one feature.

Using CLI

I want to start from implementing login module, so let’s create module using CLI.
It is so simple. Just type in powershell command

this command will create new module file in folder. Awesome! You don’t need to know best practices for organising your project, CLI does it for you.

5

The same situation is when we want to add component or service. Try it.

After executing these commands app folder looks like this. I created login.service, because it will be a part responsible for communicating with WebApi. Login.component will use this service. Unfortunately login.service is not in login folder. I want to have everything connected with login in one folder for better organisation so I will move it.

6

In official angular cli’s readme , we can see all possibillities that we have to generate files.

7

You can read more here.
Ok, project is ready to start implementation of login component. Maybe I will describe in next post how to connect WebApi. We will see 😉

[EN] Creating Angular2 CLI project

What is Angular2 CLI?

Angular2 CLI is Command Line Interface introduced by Angular team, to help us develop applications in Angular 2, through automate some operations and keep consistent project structure. You may think it’s a waste of time to learn another new thing, but I encourage you to use CLI, even if you are new to Angular. It’s even more helpful in this case, because with CLI your development will be faster and easier.


Before we start make sure you have node.js installed on your machine. If not, you can download it here
https://nodejs.org/en/download/. It is essential to develop Angular applications.

Let’s start

To create new Angular2 CLI project, open your command line tool. At the beginning you need to install angular CLI, to do it type:

1

Wait for a while, take a beer or yerba mate if you prefer and come back after few minutes 😛

Then type command that will create new project, something like this:

Where PROJECT_NAME is any name for your project. As you can see you need to wait for install packages via npm, so take another beer don’t waste your time 😉

2

After that go to project location, dig in your project folder, type cd PROJECT_NAME. You will se new files and folders here like on image below. This is our brand new project.

3

And let’s do the magic. Type ng serve and you will see…  an error maybe, but you should’n if everything you did before correctly. If everything works fine your console output should looks like this:

4

Open your browser and type http://localhost:4200 you should see:

5

It means you have working app! Congrats ;0

For developing our front end side of application, I recommend you Visual Studio Code Editor. You can download it here. https://code.visualstudio.com/

Open whole folder of your new application in VS Code

6

That’s it. Project structure and other Angular2 CLI features I will cover in the next posts.