In this tutorial, I would like to show you, how to set up an application using ASP.NET Core as an API for Angular2 frontend. You will read about Startup class in the new ASP, setting up Angular2 dependencies with NPM, configuring SystemJS, Angular2 components and services and how to connect it all together.
The whole project, which you can use as a template, can be found on GitHub.
UPDATE: There is a new tutorial available showing how to use Angular2 CLI with ASP.NET Core. I recommend using the CLI tool as it has a lot of useful features.
- Backend - ASP.NET Core based API
- Frontend - Angular2 Single Page Application
- Running the app!
- Adding a service
Backend - ASP.NET Core based API
I will start with preparing our backend service. For that, open up a Visual Studio and create an empty ASP.NET Core web project. After that, you should have a simple app ready to print “Hello World”. Let’s modify it to suit our needs.
Since we want to use MVC for the API and serve static files, you need to add following package as a dependency in the project.json file:
Now, let’s modify the Startup class, to tell asp.net to use MVC:
As you can see, I’ve added MVC setup in two places. First one is adding MVC services and second is running them. I have also added NoCache headers to everything that is run by MVC. That way I am preventing caching of API calls (common problem in IE).
Now, let’s add an index.html file, which will host the Angular2 app. It’s easily done by this piece of code added to Configure method of Startup class:
What it does is, if MVC returns 404 response and the request path does not have an extension (ex. html, jpg etc.), it will return the index.html file. It’s like a catch all, so whenever some will browse to urls for example:
It will serve this index file and angular app will pick up from there.
Frontend - Angular2 Single Page Application
At this point, we have our backend part ready. Let’s setup the frontend. First, we need to get all the packages Angular2 needs from npm. For this, you need to add a package.json file with such dependencies:
If there is a new angular version released, you can always get current package versions here: https://angular.io/docs/ts/latest/quickstart.html
We’ll also need some development tools to build our application:
To download all these packages, you need to run:
It’s also worth to add node_modules to the part setting up our index.html file, so that we get normal 404 error if there is a request for a nonexisting file in the node_modules directory:
At this point we have everything ready to start building our angular2 app. As a first step, let’s create an index.html file. The whole file is available on GitHub. In general, there are two important parts to this file.
Scripts references and base header:
Two things are happening here. One of the script imports in the head section was systemjs config file. We’ll get to it in a moment, but it’s basically a setup for all JS modules. The statement below is initialziing our application by importing it’s main file. After that, there’s a placeholder for our application.
SystemJS config file
By default, angular2 uses SystemJS module loader to manage dependencies. I won’t be going into details of how it works, because it’s not the topic of this post. The config file contains a list of packages with properties telling it, how to load these packages:
Bootstrapping the AppModule
Now, it’s time to prepare and bootstrap our application. First task is to create an app.module.ts file:
It’s basically telling Angular, which components, modules and services you’re going to use in your app.
With that done, we can bootstrap our application in the main.ts file:
Now, we can create an AppComponent.ts:
This is going to be the main component of our app. As you see, it’s template contains only the router-outlet - it’s a place, where all our content will be rendered. That said, we can now create routes definition in the app.routes.ts file:
For now, I have added just one route, to the home component we’re going to create in a moment.
Extending the app with new components
If you want to add new routes in future you just have to complete these steps:
- Create a component, for example ProductListComponent
- Add a new component in the declarations section of the main.ts file
- Add new route in the app.routes.ts file
We now have everthing wired, it’s time to create a HomeComponent:
It’s as simple as it can get. We will add something extra later on :)
Running the app!
- gulp build - builds everything and quits
- gulp watch - fires up the build command and watches for new changes. Whenever you change any file in Frondend folder, it will run build again.
I am using gulp for file processing for two reasons. First of all, it’s very fast. The watch mode is perfect for development. Files are processed in miliseconds, so when you refresh your browser, you always get new files. Secondly, it allows great control over what should be done, so it’s easy to keep your source in one folder and build to another.
When you’ve built your frontend part, you can start the application in VisualStudio. If everything went fine, you should be seeing this:
We have a ASP.NET Core application serving Angular2 app. Next step is to add an Angular2 service which will get some data from the API.
Adding a service
The best way to implement communication with the API is through the services. This way you make the app modular and much easier to test. To add a service, create a file named hello.service.ts:
You have to remmeber about few things here:
- @Injectable() decorator informs the DI system that you will require this class as a dependency in other classes
- Inject Http module in constructor
- return an Observable from the method
The greet method does not return a string - it returns an Observable of type string. This is because, all communication done with the Http module is made asynchronously. So in order to use, what was returned from the API you need to subscribe to this Observable. This is how I modified the home.component.ts:
Few things were added here:
- constructor, which gets HelloService as a dependency
- ngOnInit() - it’s a method, which is fired when the component is ready to be used. In this case it’s just invoking the greet method
- greet method - it’s using the greet method of HelloService and subscribe to it’s result.
The subscribe method of Observable get’s a function, which is invoked, when the result of an Observable is ready to be used. It’s typical way of doing things asynchronously - in other words it’s a callback method.
For all of it to work, we also need a simple API controller in our backend:
With all these changes, our app prints very nice greeting:
I think that it’s enough to digest for one post, so I will finish now. If you go to GitHub, you can see the whole project, clone it and have a play with it yourself. If you like this post and would like to see more like that, please let me know in comments below what specific subject you are interested in.