Creating a new .Net Core and Angular project using Visual Studio Code

About this project structure

I have seen some projects with angular in some blogs, but without pleasing me with the structure.

The main thing that bothered me was mixing the angular app with a webapi project. This sounds me like developing UI and service in the same layer!

I think it’s strange, so I created a structure for myself, simple as, and I would like to share with you how I solved the junction of these two worlds.

In the future I will increase this project, in another post, with IoC (which already comes with .net core, by the way).

If you are a beginner in this world of angular with .NET, be welcome!

let’s get started!

Configuring environment

First of all, you’ll need to install Node, Angular CLI, TypeScriptVisual Studio Code and .Net Core.

Be nice and:

  1. Install in that order
  2. Installing Visual Studio Code, mark to add options into your right click
  3. Install only stable versions

Trust me, it’s for your own good.

I recommend that you install Studio Icons extension on Visual Studio Code so that the project files can be more easier to see.

To do that you can press Ctrl + Shift + P, type Studio Icons, press enter and install the extension with this icon:

studio icons

Then click in reload button.

Once Visual Studio is open again, you can press Ctrl + Shift + P, type icon, press enter, and use arrow keys to select Studio Icons.

Creating basic structure

Now, create a folder wherever you want. Right Click and Open with Code.

abrir com visual studio code

I named this project as AngularCore because… Well… because I wanted to. Do this or what you want.

And yes, this is all you have right now:

new project

Press Ctrl + J to display a terminal if i’ts not visible to you:

console

Yes! A terminal!

Now you can paste all this block (may you have to press enter to execute the last one after all the others have finished):

mkdir UI
mkdir API
cd API
dotnet new webapi
dotnet restore
cd ../UI
ng new client-web-app

Hey Linux user, don’t worry! This snippet will work for you too 😉

A few explanation about these commands:

  • mkdir: Command to create folder
  • cd: Command to navigate
  • dotnet new webapi: Command to create a new web api project. Click here to see a list of dotnet commands.
  • dotnet restore: It’s like npm install command. It will read your package references (csproj file) to download all packages needed.
  • ng new [project-name]: Command to create a new angular project. Click here to more details.

Now you have this beautiful structure:

structure

Let’s take a look into API Project.

Configuring API project

Open API > Controllers > ValuesController.cs

If this is your first time with VSCode, It will show it for you:

recomendations

Click in Show recommendations, then install C# extension:

c#

Reload VSCode and open ValuesController again if it’s not opened.

Once you have ValuesController opened, VSCode will install some dependencies to you. See this on output window like below:

updating

Wait until it’s over.

If VSCode shows this to you:

prompts

  • To required assets, click in Yes.
  • To unresolved dependencies click in Restore

Change Get method without arguments to this:

// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "Hello", "World" };
}

Now, in API folder, type “dotnet run” into Terminal window:

dotnet run

And access this URL in a browser:

hello world

Or Postman:

hello world postman.PNG

Our next step is to teach the angular project how to access our api.

IMPORTANT: Don’t stop the API yet. Keep it running until the end!

Configuring Angular project

First of all, for pattern reasons, it’s a good idea, at least for me, to swap the output folder so that it matches the dotnet core output folder. By default the angular output folder is called “dist”, so we (or I) want to change it to “wwwroot”. You can put “Daisy” or “MyAwesomeMagicalAndReallyNiceFolder”, but I think that “wwwroot” is a good name for it.

To do that, open the .angular-cli.json file and change “outDir” from “dist” to “wwwroot” as follows:

wwwroot

Next, let’s consume our API.

Here we have an example to consume the API. You can replace your app.component.ts with this or make your own implementation.

import { Component, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private headers = new Headers({'Content-Type': 'application/json'});
  private valuesUrl = '/api/values';

   constructor(private http: Http) { }
   values: string[] = [];
   ngOnInit() {
      this.http.get(this.valuesUrl)
      .toPromise()
      .then(response => this.values = response.json() as string[]);
   }
}

For the above code to work, you will also need to add some imports into the app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [HttpModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

And finally, change the app.component.html to show the values:

<span *ngFor="let value of values">
   {{value}}
</span>

Not ready yet!

We still need to tell angular where to find our api because the url do not have the correct port!

If you start now the angular project, you will get a 404 message.

To resolve it, create a file called proxy.config.json at root of angular project(…)

proxy

(…) and paste this into it:

{
   "/api": {
      "target": "http://localhost:5000",
      "secure": false
   }
}

Now, open package.json and add –proxy-config proxy.config.json to ng serve script:

proxyadd

Now, all set!

And finally, to start Angular project, press plus sign on left top area of Terminal:

plus

And, in \UI\client-web-app folder, type “npm start” into Terminal window as follows:

start

Now you can see this in a browser:

end

Download entire project

You can find the complete project into this repository on GitHub.

That’s it! =)

Advertisements

2 comments

  1. Grande Galiza! óa.. no ultimo comando, o do ng, eu encontrei esse erro:
    ng : The term ‘ng’ is not recognized as the name of a cmdlet, function, script file, or operable
    program. Check the spelling of the name, or if a path was included, verify that the path is correct
    and try again.
    mas resolvi assim:

    [Windows key], type “command prompt”, right click “Run as Administrator”

    npm install -g angular-cli
    ref: https://github.com/angular/angular-cli/issues/1149

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s