Premier Projet Angular - Guide Complet

Angular est un framework JavaScript pour l'interface utilisateur. Depuis Angular 2, le langage principal de développement est devenu TypeScript plutôt que JavaScript. Cependant, la plupart des navigateurs ne prennent pas en charge l'exécution directe du code TypeScript, nécessitant l'utilisation du compilateur tsc pour convertir TypeScript en JavaScript compatible avec les navigateurs.

2 - Installation d'Angular - Ubuntu

2.1 Installation de Node et NPM

Pour installer Node.js v16.x sur Ubuntu :

# Installation de Node.js v16.x:
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs

# Installation de NPM
sudo apt install npm
# Mise à jour
npm i -g npm

2.2 Installation d'Angular et configuration du registre

$ node -v
v16.14.2
$ npm -v
8.3.1
$ npm config set registry https://registry.npmjs.org
$ npm install -g @angular/cli
/usr/bin/ng -> /usr/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@13.3.7 postinstall /usr/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

? Souhaitez-vous partager des données d'utilisation anonymes avec l'équipe Angular de Google sous
la politique de confidentialité de Google à https://policies.google.com/privacy ? Pour plus de détails
et pour savoir comment modifier ce paramètre, consultez http://angular.io/analytics. Non
+ @angular/cli@13.3.7
added 418 packages from 273 contributors in 45.742s

$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 13.3.7
Node: 16.14.2
OS: linux x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1303.7
@angular-devkit/core         13.3.7
@angular-devkit/schematics   13.3.7
@schematics/angular          13.3.7
@schematics/update           0.1303.7
rxjs                         7.5.4

2.3 Création de votre premier projet Angular

Créez une nouvelle application Angular via la ligne de commande :

$ mkdir projet-angular
$ cd projet-angular/
$ ng new mon-application

? Souhaitez-vous ajouter le routage Angular ? Oui
? Quel format de feuille de style souhaitez-vous utiliser ? SCSS

CREATE mon-application/README.md (1022 bytes)
CREATE mon-application/.editorconfig (274 bytes)
CREATE mon-application/.gitignore (631 bytes)
CREATE mon-application/angular.json (3566 bytes)
CREATE mon-application/package.json (1239 bytes)
CREATE mon-application/tsconfig.json (489 bytes)
CREATE mon-application/tslint.json (3125 bytes)
CREATE mon-application/browserslist (429 bytes)
CREATE mon-application/karma.conf.js (1018 bytes)
CREATE mon-application/tsconfig.app.json (210 bytes)
CREATE mon-application/tsconfig.spec.json (270 bytes)
CREATE mon-application/src/favicon.ico (948 bytes)
CREATE mon-application/src/index.html (291 bytes)
CREATE mon-application/src/main.ts (372 bytes)
CREATE mon-application/src/polyfills.ts (2835 bytes)
CREATE mon-application/src/styles.css (80 bytes)
CREATE mon-application/src/test.ts (753 bytes)
CREATE mon-application/src/assets/.gitkeep (0 bytes)
CREATE mon-application/src/environments/environment.prod.ts (51 bytes)
CREATE mon-application/src/environments/environment.ts (662 bytes)
CREATE mon-application/src/app/app.module.ts (314 bytes)
CREATE mon-application/src/app/app.component.css (0 bytes)
CREATE mon-application/src/app/app.component.html (25725 bytes)
CREATE mon-application/src/app/app.component.spec.ts (942 bytes)
CREATE mon-application/src/app/app.component.ts (210 bytes)
CREATE mon-application/e2e/protractor.conf.js (808 bytes)
CREATE mon-application/e2e/tsconfig.json (214 bytes)
CREATE mon-application/e2e/src/app.e2e-spec.ts (639 bytes)
CREATE mon-application/e2e/src/app.po.ts (301 bytes)
✔ Packages installés avec succès.

Démarrer l'application avec la commande "ng serve --open" dans le dossier du projet, utiliser "ctrl+c" pour arrêter :

$ cd mon-application/
$ ng serve --open

chunk {main} main.js, main.js.map (main) 57.8 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 2.71 MB [initial] [rendered]
Date: 2023-05-15T10:54:21.273Z - Hash: aeb6add91036f07e456b - Time: 19007ms
** Serveur de développement Angular Live écoutant sur localhost:4200, ouvrez votre navigateur sur http://localhost:4200/ **
: Compilation réussie.

Structure des répertoires et fichiers

  • src - Répertoire des fichiers source - app - Contient le code source de l'application, composants et modules - assets - Fichiers de ressources statiques - environments - Configurations d'environnement - index.html - Fichier HTML racine de l'application - main.ts - Fichier d'entrée de l'application - polyfills.ts - Fichier de compatibilité avec les navigateurs - styles.css - Fichier de styles globaux

2.4 Effectuer vos premières modifications

Modifiez le fichier du composant principal pour afficher un message personnalisé :

$ > src/app/app.component.html
$ vim src/app/app.component.html

Contenu du fichier HTML :

<h1>Bonjour {{ nomApplication }} !</h1>

Modifiez le fichier TypeScript du composant :

$ cat src/app/app.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  nomApplication = 'mon-application';

  ngOnInit() {
    this.nomApplication = 'Angular';
  }
}

Démarrez à nouveau l'application pour voir les changements :

$ ng serve --open

chunk {main} main.js, main.js.map (main) 9.49 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 2.71 MB [initial] [rendered]
Date: 2023-05-15T10:25:28.098Z - Hash: fa77f4f8a5fe207072c6 - Time: 17337ms
** Serveur de développement Angular Live écoutant sur localhost:4200, ouvrez votre navigateur sur http://localhost:4200/ **
: Compilation réussie.

3 - Compilation

Angular propose deux modes de compilation : AoT (Ahead-of-Time) et JiT (Just-in-Time).

  • AoT : Le code est compilé lors du build, le navigateur charge du code déjà pré-compilé
  • JiT : Le code est compilé à chaque exution dans le navigateur

La compilation AoT accélère le temps de démarrage de l'application, réduit la taille des scripts et permet de détecter les erreurs plus tôt. En production, le mode AoT est généralement préféré.

Utilisez la commande suivante pour compiler avec AoT et tree shaking (méthode recommandée) :

$ ng build --prod

Exécutez cette commande dans le répertoire du projet pour créer une version de production :

$ cd mon-application/
$ ng build --prod

Génération des bundles ES5 pour le chargement différentiel...
Génération des bundles ES5 terminée.

chunk {0} runtime-es2015.1eba213af0b233498d9d.js (runtime) 1.45 kB [entry] [rendered]
chunk {0} runtime-es5.1eba213af0b233498d9d.js (runtime) 1.45 kB [entry] [rendered]
chunk {1} main-es2015.8cffd84673dc9f7dee27.js (main) 104 kB [initial] [rendered]
chunk {1} main-es5.8cffd84673dc9f7dee27.js (main) 125 kB [initial] [rendered]
chunk {2} polyfills-es2015.690002c25ea8557bb4b0.js (polyfills) 36.1 kB [initial] [rendered]
chunk {3} polyfills-es5.9e286f6d9247438cbb02.js (polyfills-es5) 129 kB [initial] [rendered]
chunk {4} styles.3ff695c00d717f2d2a11.css (styles) 0 bytes [initial] [rendered]
Date: 2023-05-15T10:29:13.307Z - Hash: 3fd2a82c970e630020b8 - Time: 67976ms

Un nouveau répertoire "dist" est créé avec tous les fichiers déployables :

$ tree dist/
dist/
└── mon-application
    ├── 3rdpartylicenses.txt
    ├── favicon.ico
    ├── index.html
    ├── main-es2015.8cffd84673dc9f7dee27.js
    ├── main-es5.8cffd84673dc9f7dee27.js
    ├── polyfills-es2015.690002c25ea8557bb4b0.js
    ├── polyfills-es5.9e286f6d9247438cbb02.js
    ├── runtime-es2015.1eba213af0b233498d9d.js
    ├── runtime-es5.1eba213af0b233498d9d.js
    └── styles.3ff695c00d717f2d2a11.css

1 répertoire, 10 fichiers

4 - Déploiement

Cloud Foundry est une plateforme PaaS open source qui permet de déployer des applications dans le cloud. Le CLI Cloud Foundry est utilisé pour déployer les applications avec un fichier manifest.yml.

4.1 Création du fichier manifest

$ cat manifest.yml
---
applications:
  - name: 'test-angular-deploiement'
    buildpack: staticfile_buildpack
    stack: cflinuxfs3
    command: "$HOME/boot.sh"
    memory: 256M
    disk_quota: 1G
    instances: 1
    routes:
      - route: test-angular-deploiement.apps.sea.preview.pcf.manulife.com

4.2 Utilisation de PCF

Connectez-vous à l'espace approprié sur PCF :

$ cf login -a https://api.sys.sea.preview.pcf.manulife.com
Point de terminaison API : https://api.sys.sea.preview.pcf.manulife.com

Identifiant LAN : monidentifiant

Mot de passe :
Authentification...
OK

Sélectionnez une organisation :
1. ASIAREGIONAL-SEA-DEV
2. ASIAREGIONAL-SEA-SIT
3. SANDBOX

Organisation (laisser vide pour ignorer) : 3
Organisation ciblée SANDBOX

Espace ciblé monespace

Point de terminaison API :   https://api.sys.sea.preview.pcf.manulife.com (version API : 3.74.0)
Utilisateur :           monidentifiant
Organisation :            SANDBOX
Espace :          monespace

Déployez l'application Angular sur Cloud Foundry :

$ cd mon-application/
$ cf push -f ../manifest.yml

Pushing from manifest to org SANDBOX / space monespace as monidentifiant...
Using manifest file C:\TempFiles\dist\manifest.yml

Getting app info...
Creating app with these attributes...
+ name:         test-angular-deploiement
  path:         C:\TempFiles\dist\mon-application
  buildpacks:
+   staticfile_buildpack
+ command:      $HOME/boot.sh
+ instances:    1
+ stack:        cflinuxfs3
  routes:
+   test-angular-deploiement.apps.sea.preview.pcf.manulife.com

Creating app test-angular-deploiement...
Mapping routes...
Comparing local files to remote cache...
Packaging files to upload...
Uploading files...
 90.26 KiB / 90.26 KiB [==============================================================================================================================================================================] 100.00% 1s

Waiting for API to complete processing files...

Staging app and tracing logs...
   Downloading staticfile_buildpack...
   Downloaded staticfile_buildpack
   Cell d6cf5115-3004-4b39-9fc2-74240632a4fe creating container for instance 1fd44705-8280-4a83-a389-dc40b6c5ee77
   Cell d6cf5115-3004-4b39-9fc2-74240632a4fe successfully created container for instance 1fd44705-8280-4a83-a389-dc40b6c5ee77
   Downloading app package...
   Downloaded app package (134.4K)
   -----> Staticfile Buildpack version 1.5.3
   -----> Installing nginx
          Using nginx version 1.17.7
   -----> Installing nginx 1.17.7
          Copy [/tmp/buildpacks/97cfca992a4e376f88429cb596e30523/dependencies/bf75ee5ff33a7fb3f3e747caf653b7c3/nginx-1.17.7-linux-x64-cflinuxfs3-2197ee1f.tgz]
          **ATTENTION** nginx 1.17.x ne sera plus disponible dans les nouveaux buildpacks publiés après 2020-05-01.
          Voir : https://nginx.org/
   -----> Root folder /tmp/app
   -----> Copying project files into public
   -----> Configuring nginx
   Exit status 0
   Uploading droplet, build artifacts cache...
   Uploading build artifacts cache...
   Uploading droplet...
   Uploaded build artifacts cache (218B)
   Uploaded droplet (2.2M)
   Uploading complete
   Cell d6cf5115-3004-4b39-9fc2-74240632a4fe stopping instance 1fd44705-8280-4a83-a389-dc40b6c5ee77
   Cell d6cf5115-3004-4b39-9fc2-74240632a4fe destroying container for instance 1fd44705-8280-4a83-a389-dc40b6c5ee77
   Cell d6cf5115-3004-4b39-9fc2-74240632a4fe successfully destroyed container for instance 1fd44705-8280-4a83-a389-dc40b6c5ee77

Waiting for app to start...

name:                test-angular-deploiement
requested state:     started
isolation segment:   SEA-MOV
routes:              test-angular-deploiement.apps.sea.preview.pcf.manulife.com
last uploaded:       Mon 15 May 16:05:46 CST 2023
stack:               cflinuxfs3
buildpacks:          static

type:            web
instances:       1/1
memory usage:    1024M
start command:   $HOME/boot.sh
     state     since                  cpu    memory    disk      details
#0   running   2023-05-15T08:05:56Z   0.0%   0 of 1G   0 of 1G

4.3 Vérification du statut

Vérifiez que l'application est bien déployée et fonctionne :

$ cf apps
Getting apps in org SANDBOX / space monespace as monidentifiant...
OK

name                  requested state   instances   memory   disk   urls
test-angular-deploiement   started           1/1         1G       1G     test-angular-deploiement.apps.sea.preview.pcf.manulife.com

5 - Résolution de problèmes

Problème : La commande ng n'est pas reconnue après installation

$ npm install -g @angular/cli
$ ng -v
'ng' n'est pas reconnu en tant que commande interne ou externe,
un programme exécutable ou un fichier de commandes.

Solution

Angular est installé dans le répertoire npm, il faut ajouter ce chemin aux variables d'environnement PATH. Si la commande "ng --version" affiche correctement les informations de version, l'installation est réussie.

$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 13.3.7
Node: 16.14.2
OS: win32 x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1303.7
@angular-devkit/core         13.3.7
@angular-devkit/schematics   13.3.7
@schematics/angular          13.3.7
@schematics/update           0.1303.7
rxjs                         7.5.4

Étiquettes: Angular TypeScript Cloud Foundry Déploiement Node.js

Publié le 1 juin à 15h57