Перейти к содержимому

Как создать проект angular

  • автор:

Создание приложения Angular

Область применения:yesVisual Studio Visual Studio для Mac noVisual Studio Code no

В рамках этого краткого (на 5–10 минут) знакомства с возможностями интегрированной среды разработки (IDE) Visual Studio вы создадите и запустите простое внешнее веб-приложение Angular.

Необходимые компоненты

Обязательно установите следующие компоненты:

  • Visual Studio 2022 или более поздней версии. Перейдите на страницу скачиваемых материалов Visual Studio, чтобы установить ее бесплатно.
  • npm (https://www.npmjs.com/), который входит в состав Node.js
  • CLI Angular (https://angular.io/cli). Версия может быть любой на ваш выбор.

Создание своего приложения

  1. В окне запуска (чтобы открыть его, щелкните Файл>Окно запуска) выберите Создание нового проекта. Screenshot showing Create a new project
  2. Найдите Angular в строке поиска в верхней части и выберите автономный проект TypeScript Angular. Screenshot showing choosing a template
  3. Присвойте имена проекту и решению. Когда откроется окно «Дополнительные сведения», НЕ устанавливайте флажок Добавить интеграцию для пустого проекта веб-API ASP.NET. Этот параметр добавляет файлы в шаблон Angular, чтобы позже его можно было связать с проектом ASP.NET Core, если проект ASP.NET Core был добавлен. Screenshot showing Additional information
  4. Нажмите кнопку «Создать«, а затем дождитесь создания проекта в Visual Studio.

Просмотр свойств проекта

Параметры проекта по умолчанию позволяют выполнить сборку и отладку проекта. Но если вам нужно изменить параметры, щелкните правой кнопкой мыши проект в Обозреватель решений, выберите Свойства, а затем перейдите в раздел Сборка или Отладка.

Файл launch.json хранит параметры запуска, связанные с кнопкой Запуск на панели инструментов отладки. В настоящее время файл launch.json должен находиться в папке .vscode.

Сборка проекта

Выберите Сборка>Собрать решение, чтобы собрать проект.

Обратите внимание, что начальная сборка может занять некоторое время, так как Angular CLI будет выполнять команду установки npm.

Запуск проекта

Нажмите клавишу F5 или кнопку Запуск в верхней части окна, чтобы открыть командную строку.

    Выполнение команды ng start в Angular CLI

Примечание. Проверьте наличие в консоли сообщений, например сообщения с указанием обновить версию Node.js.

После этого откроются базовые приложения Angular.

Следующие шаги

Интеграция ASP.NET Core

Как создать проект angular

В предыдущей теме были рассмотрены начальная информация об Angular и установка необходимых инструментов и настройка конфигурации для работы с фреймворком. Теперь же создадим первое приложение.

Для написания приложений нам потребуется обычный текстовый редактор, хотя можно использовать специальные среды программирования, как Visual Studio, Netbeans, WebStorm и другие.

Кроме того, для запуска приложения Angular потребуется веб-сервер. В качестве веб-сервера опять же можно использовать множество различных серверов — Apache, IIS, NodeJS и т.д. В данном случае мы будем опираться на NodeJS.

Итак, создадим на жестком диске папку приложения. Путь она будет называться purchaseapp . В этой папке создадим новый файл package.json со следующим содержимым:

< "name": "purchaseapp", "version": "1.0.0", "description": "First Angular 17 Project", "author": "Eugene Popov metanit.com", "scripts": < "ng": "ng", "start": "ng serve", "build": "ng build" >, "dependencies": < "@angular/common": "~17.0.0", "@angular/compiler": "~17.0.0", "@angular/core": "~17.0.0", "@angular/forms": "~17.0.0", "@angular/platform-browser": "~17.0.0", "@angular/platform-browser-dynamic": "~17.0.0", "@angular/router": "~17.0.0", "rxjs": "~7.8.0", "zone.js": "~0.14.2" >, "devDependencies": < "@angular-devkit/build-angular": "~17.0.0", "@angular/cli": "~17.0.0", "@angular/compiler-cli": "~17.0.0", "typescript": "~5.2.2" >>

Также добавим в папку проекта новый файл tsconfig.json :

< "compileOnSave": false, "compilerOptions": < "baseUrl": "./", "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "module": "ES2022", "moduleResolution": "node", "target": "ES2022", "typeRoots": [ "node_modules/@types" ], "lib": [ "ES2022", "dom" ] >, "files": [ "src/main.ts"], "include": [ "src/**/*.d.ts" ] >

Как было уже описано в прошлой теме, файл package.json устанавливает пакеты и зависимости, которые будут использоваться проектом.

Файл tsconfig.json устанавливает конфигурацию для компилятора TypeScript.

Для сборки проекта будем использовать Angular CLI, поэтому также определим в папке проекта файл angular.json :

 < "version": 1, "projects": < "purchaseapp": < "projectType": "application", "root": "", "sourceRoot": "src", "architect": < "build": < "builder": "@angular-devkit/build-angular:browser", "options": < "outputPath": "dist/purchaseapp", "index": "src/index.html", "main": "src/main.ts", "polyfills": ["zone.js"], "tsConfig": "tsconfig.json", "aot": true >>, "serve": < "builder": "@angular-devkit/build-angular:dev-server", "options": < "buildTarget": "purchaseapp:build" >> > > > >

После создания этих трех файлов в папке проекта откроем командную строку (терминал) и перейдем в ней к папке проекта с помощью команды cd:

C:\WINDOWS\system32>cd C:\angular\purchaseapp

И затем выполним команду npm install , которая установит все необходимые модули:

C:\angular\purchaseapp>npm install

После выполнения этой команды в папке проекта должна появиться подпапка node_modules , которая содержит все используемые зависимости и пакеты.

Затем создадим в папке проекта каталог src , а в этом каталоге определим папку app .

В каталог src/app добавим новый файл, который назовем app.component.ts и который будет иметь следующий код:

import < Component >from "@angular/core"; import < FormsModule >from "@angular/forms"; class Item < purchase: string; done: boolean; price: number; constructor(purchase: string, price: number) < this.purchase = purchase; this.price = price; this.done = false; >> @Component( < selector: "purchase-app", standalone: true, imports: [FormsModule], template: ` 

Список покупок



@for (item of items; track item.purchase) < >
Предмет Цена Куплено
> >
` >) export class AppComponent < text: string = ""; price: number = 0; items: Item[] = [ < purchase: "Хлеб", done: false, price: 15.9 >, < purchase: "Масло", done: false, price: 60 >, < purchase: "Картофель", done: true, price: 22.6 >, < purchase: "Сыр", done: false, price:310 >]; addItem(text: string, price: number): void < if(text==null || text.trim()=="" || price==null) return; this.items.push(new Item(text, price)); >>

Двумя первыми строками здесь импортируется функциональность компонента из angular/core и модуль FormsModule из пакета «angular/forms».

Для работы нам потребуется вспомогательный класс Item. Этот класс содержит три поля: purchase (название покупки), done (сделана ли покупка) и price (ее цена).

В самом классе компонента определяется начальный список покупок, который будет выводиться на страницу:

items: Item[] = [ < purchase: "Хлеб", done: false, price: 15.9 >, < purchase: "Масло", done: false, price: 60 >, < purchase: "Картофель", done: true, price: 22.6 >, < purchase: "Сыр", done: false, price:310 >];

И также в классе определен метод добавления в этот список:

addItem(text: string, price: number): void

Для вывода покупок здесь определен большой шаблон. Вообще подобные большие шаблоны стоит выносить в отдельные файлы, чтобы сделать код компонента проще. Но в нашем случае пусть все пока будет определено в самом компоненте.

В самом шаблоне для вывода данных из массива items в таблицу предусмотрена директива:

@for (item of items; track item.purchase) < > >   >

Кроме того, сверху от таблицы расположена форма для ввода нового объекта Item. А к нажатию кнопки привязан метод addItem() компонента.

Уровнем выше в каталоге src определим файл main.ts для запуска проекта:

import < bootstrapApplication >from "@angular/platform-browser"; import < AppComponent >from "./app/app.component"; bootstrapApplication(AppComponent).catch(e => console.error(e));

Здесь с помощью функции bootstrapApplication запускается приложение в виде выше определенного компонента AppComponent.

В конце определим главную страницу index.html в папке src :

    Приложение покупок Загрузка.   

В итоге у нас получится следующая структура проекта:

Проект Angular и TypeScript

Теперь запустим проект. Для этого в командной строке (терминале) перейдем к папке проекта и затем выполним команду ng serve :

C:\angular\purchaseapp>ng serve --open

После этого в веб-браузере обратимся к нашему приложению и увидем таблицу с покупками и форму для добавлени новой покупки:

Как правильно собрать проект angular-cli?

Создал проект через ng new. Далее запустил ничего не изменяя, всё работает. Проробывал собрать его через ng build —prod, всё прошло успешно, появился папка dist c index.html и другими скриптами для работы angular. Открыл index.html в браузере, а там ничего нет, пустая страница, хоть в коде всё прописанно и подключено. Может я что-то делаю не правиль, просто я новичок в angular. Прошу вашей помощи.

Отслеживать
задан 20 янв 2018 в 3:08
1 1 1 серебряный знак 2 2 бронзовых знака
Попробуйте запусить index.html не просто в браузере, а через какой-нибуь веб-серве.
20 янв 2018 в 8:25

4 ответа 4

Сортировка: Сброс на вариант по умолчанию

для запуска в режиме разработчика:

ng serve 
ng build --prod 
ng build --prod --aot 

если надо запустить на определенном порте/хосту:

ng serve --env=dev --host 127.0.0.1 --port 4200 

Переходм из браузера на:

Отслеживать
ответ дан 16 фев 2018 в 5:00
374 1 1 серебряный знак 5 5 бронзовых знаков

По-хорошему требуется запустить ng serve — команда соберет проект, создаст на localhost:4200 локальный сервер и начнет отслеживание изменений исходного кода для пересборки в реальном времени. Вы пишите — все обновляется на лету.

Отслеживать
ответ дан 22 янв 2018 в 6:29
Roman Pertsev Roman Pertsev
445 2 2 серебряных знака 6 6 бронзовых знаков

Команда ng build —prod собирает Ваш проект в папку dist или в любую другую папку которую Вы укажете в свойстве «outDir»: «dist», файла angular-cli.json. Проект будет собран с включенной AOT компиляцией, минификацией кода, а так же будут включены некоторые другие функции оптимизации (подробнее).

В папке dist index.html будет минифицирован, откройте его и посмотрите есть ли там вообще что то, в самом файле, далее требуется содержимое папки dist расположить на Вашем локальном веб-сервере или на хостинге, как Вам удобнее, после этого проверьте как все работает.

Команда ng serve собирает проект, но так же располагает его на веб-сервере, соответственно весь функционал оптимизации отключен. Если я не путаю, то в данном случае использует webpack-dev-server встроенный в angular-cli.

Руководство. Подготовка одностраничного приложения Angular для проверки подлинности в клиенте клиента

В предыдущей статье подготовьте клиент клиента для проверки подлинности пользователей в одностраничного приложения Angular (SPA), вы зарегистрировали приложение и настроили потоки пользователей в Внешняя идентификация Microsoft Entra для клиентов. В этом руководстве показано, как создать одностраничные приложения Angular с помощью npm и настроить пользовательский интерфейс.

В этом руководстве;

  • Создание проекта Angular в Visual Studio Code
  • Настройка пользовательского интерфейса для приложения
  • Настройка домашних и защищенных компонентов

Необходимые компоненты

  • Хотя любую интегрированную среду разработки (IDE), поддерживающую приложения Angular, можно использовать, в этом руководстве используется Visual Studio Code. Вы можете скачать VS Code здесь.
  • Node.js.

Создание проекта Angular

В этом разделе мы создадим проект Angular с помощью Angular CLI в Visual Studio Code.

  1. Откройте Visual Studio Code, выберите «Открыть папку» >. Перейдите к папке, в которой вы хотите создать проект, и выберите его расположение.
  2. Откройте новый терминал, выбрав терминал >»Новый терминал».
  3. Выполните следующие команды, чтобы создать новый проект Angular с именем angularspalocal , установить библиотеки компонентов Angular Material, MSAL Browser, MSAL Angular и создать домашние и защищенные компоненты.

npm install -g @angular/cli@14.2.0 ng new angularspalocal --routing=true --style=css --strict=false cd angularspalocal npm install @angular/material@13.0.0 @angular/cdk@13.0.0 npm install @azure/msal-browser@2.37.0 @azure/msal-angular@2.5.7 ng generate component home ng generate component guarded 

Настройка элементов пользовательского интерфейса

Следующие шаги по настройке элементов пользовательского интерфейса приложения. Стилизация CSS добавляется в приложение для определения цветов и шрифтов. Верхний и нижний колонтитул приложения определяются в HTML-файле, а стилизация CSS добавляется на домашнюю страницу приложения.

    Откройте src/styles.css и замените существующий код следующим фрагментом кода.

@import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; html, body < height: 100%; >body
  > 
Guarded Component
Share your experience with us!
.toolbar-spacer < flex: 1 1 auto; >a.title < color: white; >footer < position: fixed; left: 0; bottom: 0; width: 100%; color: white; text-align: center; >.footer-text

Настройка компонентов приложения

В этом разделе описана настройка домашних и защищенных компонентов приложения. Домашний компонент является целевой страницей приложения, а защищенный компонент — это страница, доступная только для прошедших проверку подлинности пользователей.

    Откройте src/app/home/home.component.ts и замените существующий код следующим фрагментом кода.

import < Component, Inject, OnInit >from '@angular/core'; import < Subject >from 'rxjs'; import < filter >from 'rxjs/operators'; import < MsalBroadcastService, MsalGuardConfiguration, MsalService, MSAL_GUARD_CONFIG >from '@azure/msal-angular'; import < AuthenticationResult, InteractionStatus, InteractionType >from '@azure/msal-browser'; import < createClaimsTable >from '../claim-utils'; @Component(< selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], >) export class HomeComponent implements OnInit < loginDisplay = false; dataSource: any = []; displayedColumns: string[] = ['claim', 'value', 'description']; private readonly _destroying$ = new Subject(); constructor( @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration, private authService: MsalService, private msalBroadcastService: MsalBroadcastService ) < >ngOnInit(): void < this.msalBroadcastService.inProgress$ .pipe( filter((status: InteractionStatus) =>status === InteractionStatus.None) ) .subscribe(() => < this.setLoginDisplay(); this.getClaims( this.authService.instance.getActiveAccount()?.idTokenClaims ); >); > setLoginDisplay() < this.loginDisplay = this.authService.instance.getAllAccounts().length >0; > getClaims(claims: any) < if (claims) < const claimsTable = createClaimsTable(claims); this.dataSource = [. claimsTable]; >> signUp() < if (this.msalGuardConfig.interactionType === InteractionType.Popup) < this.authService.loginPopup(< scopes: [], prompt: 'create', >) .subscribe((response: AuthenticationResult) => < this.authService.instance.setActiveAccount(response.account); >); > else < this.authService.loginRedirect(< scopes: [], prompt: 'create', >); > > // unsubscribe to events when component is destroyed ngOnDestroy(): void < this._destroying$.next(undefined); this._destroying$.complete(); >> 

 Angular single-page application built with MSAL Angular Sign in with Microsoft Entra External ID for customers This sample demonstrates how to configure MSAL Angular to sign up, sign in and sign out with Microsoft Entra External ID for customers   

See below the claims in your ID token . For more information, visit: docs.microsoft.com

Claim > Value > Description >
#table-container < height: '100vh'; overflow: auto; >table < margin: 3% auto 1% auto; width: 70%; >.mat-row < height: auto; >.mat-cell < padding: 8px 8px 8px 0; >p < text-align: center; >.card-section
import < Component, OnInit >from '@angular/core'; @Component(< selector: 'app-guarded', templateUrl: './guarded.component.html', styleUrls: ['./guarded.component.css'] >) export class GuardedComponent implements OnInit < constructor() < >ngOnInit(): void < >> 
/** * Populate claims table with appropriate description * @param claims ID token claims * @returns claimsTable */ export const createClaimsTable = (claims: Record): any[] => < const claimsTable: any[] = []; Object.keys(claims).map((key) => < switch (key) < case 'aud': populateClaim( key, claims[key], "Identifies the intended recipient of the token. In ID tokens, the audience is your app's Application ID, assigned to your app in the Azure portal.", claimsTable ); break; case 'iss': populateClaim( key, claims[key], 'Identifies the issuer, or authorization server that constructs and returns the token. It also identifies the Azure AD tenant for which the user was authenticated. If the token was issued by the v2.0 endpoint, the URI will end in /v2.0.', claimsTable ); break; case 'iat': populateClaim( key, changeDateFormat(+claims[key]), '"Issued At" indicates the timestamp (UNIX timestamp) when the authentication for this user occurred.', claimsTable ); break; case 'nbf': populateClaim( key, changeDateFormat(+claims[key]), 'The nbf (not before) claim dictates the time (as UNIX timestamp) before which the JWT must not be accepted for processing.', claimsTable ); break; case 'exp': populateClaim( key, changeDateFormat(+claims[key]), "The exp (expiration time) claim dictates the expiration time (as UNIX timestamp) on or after which the JWT must not be accepted for processing. It's important to note that in certain circumstances, a resource may reject the token before this time. For example, if a change in authentication is required or a token revocation has been detected.", claimsTable ); break; case 'name': populateClaim( key, claims[key], "The name claim provides a human-readable value that identifies the subject of the token. The value isn't guaranteed to be unique, it can be changed, and it's designed to be used only for display purposes. The 'profile' scope is required to receive this claim.", claimsTable ); break; case 'preferred_username': populateClaim( key, claims[key], 'The primary username that represents the user. It could be an email address, phone number, or a generic username without a specified format. Its value is mutable and might change over time. Since it is mutable, this value must not be used to make authorization decisions. It can be used for username hints, however, and in human-readable UI as a username. The profile scope is required in order to receive this claim.', claimsTable ); break; case 'nonce': populateClaim( key, claims[key], 'The nonce matches the parameter included in the original /authorize request to the IDP.', claimsTable ); break; case 'oid': populateClaim( key, claims[key], 'The oid (user object id) is the only claim that should be used to uniquely identify a user in an Azure AD tenant.', claimsTable ); break; case 'tid': populateClaim( key, claims[key], 'The id of the tenant where this application resides. You can use this claim to ensure that only users from the current Azure AD tenant can access this app.', claimsTable ); break; case 'upn': populateClaim( key, claims[key], 'upn (user principal name) might be unique amongst the active set of users in a tenant but tend to get reassigned to new employees as employees leave the organization and others take their place or might change to reflect a personal change like marriage.', claimsTable ); break; case 'email': populateClaim( key, claims[key], 'Email might be unique amongst the active set of users in a tenant but tend to get reassigned to new employees as employees leave the organization and others take their place.', claimsTable ); break; case 'acct': populateClaim( key, claims[key], 'Available as an optional claim, it lets you know what the type of user (homed, guest) is. For example, for an individual’s access to their data you might not care for this claim, but you would use this along with tenant id (tid) to control access to say a company-wide dashboard to just employees (homed users) and not contractors (guest users).', claimsTable ); break; case 'sid': populateClaim( key, claims[key], 'Session ID, used for per-session user sign-out.', claimsTable ); break; case 'sub': populateClaim( key, claims[key], 'The sub claim is a pairwise identifier - it is unique to a particular application ID. If a single user signs into two different apps using two different client IDs, those apps will receive two different values for the subject claim.', claimsTable ); break; case 'ver': populateClaim( key, claims[key], 'Version of the token issued by the Microsoft identity platform', claimsTable ); break; case 'login_hint': populateClaim( key, claims[key], 'An opaque, reliable login hint claim. This claim is the best value to use for the login_hint OAuth parameter in all flows to get SSO.', claimsTable ); break; case 'idtyp': populateClaim( key, claims[key], 'Value is app when the token is an app-only token. This is the most accurate way for an API to determine if a token is an app token or an app+user token', claimsTable ); break; case 'uti': case 'rh': break; default: populateClaim(key, claims[key], '', claimsTable); >>); return claimsTable; >; /** * Populates claim, description, and value into an claimsObject * @param claim * @param value * @param description * @param claimsObject */ const populateClaim = ( claim: string, value: string, description: string, claimsTable: any[] ): void => < claimsTable.push(< claim: claim, value: value, description: description, >); >; /** * Transforms Unix timestamp to date and returns a string value of that date * @param date Unix timestamp * @returns */ const changeDateFormat = (date: number) => < let dateObj = new Date(date * 1000); return `$- [$]`; >; 
    Microsoft identity platform         

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *