Asp.net core et angular

De Banane Atomic
Révision datée du 20 septembre 2018 à 14:58 par Nicolas (discussion | contributions)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Aller à la navigationAller à la recherche

Webpack Dev Middleware - aspnet-webpack

Permet de:

  • recompiler les modifications faite dans angular
  • recharger la page pour afficher les éléments modifiés
Fonctionne seulement en debug

VS code

Bash.svg
# création d'un projet MVC - angular
dotnet new angular -o MyApp

# installation des dépendances .net
# optionnel car vscode le fait aussi
cd MyApp
dotnet restore

# installation des packets node.js listés dans le fichier package.json
cd ClientApp
yarn

Modules:

Template WebAPI .NET Core 2.1 + Angular 6

Powershell.svg
# création du projet .NET Core à partir du template WebAPI
dotnet new webapi -o .\DotNetCoreWebApiAngular6

# ajout d'un projet Angular 6
cd DotNetCoreWebApiAngular6
ng new ClientApp
Startup.cs
using Microsoft.AspNetCore.SpaServices.AngularCli;

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    // Microsoft.AspNetCore.SpaServices middleware
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
    app.UseSpaStaticFiles();

    app.UseMvc();

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";
 
        if (env.IsDevelopment())
        {
            spa.UseAngularCliServer(npmScript: "start");
        }
    });

Appel web api

ClientApp\src\app\app.component.ts
import { HttpClient } from '@angular/common/http';

export class AppComponent {
  title = 'app';
  public values: string[];

  constructor(private http: HttpClient) {
    this.http.get('/api/values').subscribe(result => {
      this.values = result as string[];
    }, error => console.error(error));
  }
ClientApp\src\app\app.module.ts
import { HttpClientModule } from '@angular/common/http';

imports: [
    BrowserModule,
    HttpClientModule
  ],
ClientApp\src\app\app.component.html
<h3>Data coming from server values API</h3>
<ul>
  <li *ngFor="let value of values">
    {{ value }}
  </li>
</ul>

Debug Angular avec VScode et Firefox

  • Installer Debugger for Firefox
  • Ajouter un nouvel élément de lancement
.vscode\launch.json
{
    "name": "Debug Angular",
    "type": "firefox",
    "request": "launch",
    "reAttach": true,
    "url": "http://localhost:5000",
    "webRoot": "${workspaceFolder}/ClientApp"
}
  • Lancer le service Web API ainsi que le service Angular : dotnet run --ASPNETCORE_ENVIRONMENT Development
  • Lancer le débogage depuis VS code: Debug → Debug Angular → Run

Template Angular .net core

Template Angular .net core 2.1

  1. Installer dotnet core 2.1.300 preview
  2. Installer VS 2017 preview 15.8
Package JS Version
@angular/* ^5.0.0
@angular/cli 1.6.3
bootstrap 3.3.7

MAJ vers Angular 6

Powershell.svg
yarn upgrade @angular/animations@latest @angular/common@latest @angular/compiler@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest

yarn upgrade rxjs@latest
yarn upgrade @nguniversal/module-map-ngfactory-loader@latest
yarn upgrade @angular/compiler-cli@latest
yarn upgrade typescript@^2.7.2
fail: Microsoft.AspNetCore.SpaServices[0]
      Version of @angular/compiler-cli needs to be 2.3.1 or greater. Current version is "6.0.5".

fail: Microsoft.AspNetCore.SpaServices[0]
      Error: Version of @angular/compiler-cli needs to be 2.3.1 or greater. Current version is "6.0.5".

Template Angular .net core 2.0

Package JS Version
@angular/* 4.2.5
webpack 2.5.1
bootstrap 3.3.7
jquery 3.2.1

Màj vers Angular 4.3.0

Can't resolve all parameters for HttpXsrfCookieExtractor

Erreur après la màj d'angular 4.2.5 vers 4.3.0 dans un projet angular .net core

Bash.svg
node_modules/.bin/webpack --config webpack.config.vendor.js

Angular 6 + Template MVC .NET Core 2.0

Ajout d'une application Angular

Powershell.svg
ng new myapp

mkdir ClientApp
cp -r .\myapp\src\* .\ClientApp\
cp .\myapp\tsconfig.json .
cp .\myapp\angular.json .

# merger les fichiers package.json et myapp\package.json
yarn add package-json-merge --optional
.\node_modules\.bin\package-json-merge.cmd .\package.json .\angular-app\package.json > .\package-merged.json
mv .\package.json .\package.json.bak
mv .\package-merged.json .\package.json

# installer les paquets manquant
yarn install

Modifier les fichiers pour corriger les chemins

tsconfig.json
{
  "compileOnSave": false,
  // ajout de include
  "include": [
    "./ClientApp",
    "./wwwroot/ts"
  ],
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./wwwroot/clientapp/out-tsc",  // modifier le chemin
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
angular.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-app": {
      "root": "",
      "sourceRoot": "ClientApp",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "./wwwroot/clientapp/dist",
            "index": "ClientApp/index.html",
            "main": "ClientApp/main.ts",
            "polyfills": "ClientApp/polyfills.ts",
            "tsConfig": "ClientApp/tsconfig.app.json",
            "assets": [
              "ClientApp/favicon.ico",
              "ClientApp/assets"
            ],
            "styles": [
              "ClientApp/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "ClientApp/environments/environment.ts",
                  "with": "ClientApp/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "angular-app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "ClientApp/test.ts",
            "polyfills": "ClientApp/polyfills.ts",
            "tsConfig": "ClientApp/tsconfig.spec.json",
            "karmaConfig": "ClientApp/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [],
            "assets": [
              "ClientApp/favicon.ico",
              "ClientApp/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "ClientApp/tsconfig.app.json",
              "ClientApp/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "angular-app-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "angular-app:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "angular-app"
}
Powershell.svg
# test que tout est bon
ng build

Intégration

Views/Items/Index.cshtml
@section Scripts {
<script src="~/clientapp/dist/runtime.js"></script>
<script src="~/clientapp/dist/polyfills.js"></script>
<script src="~/clientapp/dist/styles.js"></script>
<script src="~/clientapp/dist/vendor.js"></script>
<script src="~/clientapp/dist/main.js"></script>
}

<app-root></app-root>

ng generate component (template angular .net core 2.1)

Your global Angular CLI version (6.0.7) is greater than your local
version (1.6.3). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
internal/modules/cjs/loader.js:596
    throw err;
    ^

Error: Cannot find module '@angular-devkit/core'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
    at Function.Module._load (internal/modules/cjs/loader.js:520:25)
    at Module.require (internal/modules/cjs/loader.js:650:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (C:\Users\llobera\source\repos\DotnetcoreAngular-4\ClientApp\node_modules\@angular-devkit\schematics\src\tree\virtual.js:10:16)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
La màj de @angular/cli créé d'autres problèmes.
Bash.svg
yarn add @angular-devkit/core@0.0.29
# utilisation d'angular-cli local
yarn ng generate component 'images'