Это путешествие началось с моего первого знакомства с Angular, широко используемым интерфейсным фреймворком. Как и в случае с любым новым программным обеспечением, я столкнулся с некоторыми трудностями, но мне удалось их преодолеть. Этот рассказ документирует, как я решил эти проблемы.
Начнем со снимка моего окружения. Я работал на MacBook, как показано ниже:
Что касается моей рабочей среды, то первой проблемой, с которой я столкнулся, была «Ошибка: EACCES: разрешение отклонено», как показано ниже:
➜ DatingApp git:(master) npm install -g @angular/cli npm ERR! code EACCES npm ERR! syscall mkdir npm ERR! path /usr/local/lib/node_modules/@angular npm ERR! errno -13 npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/@angular' npm ERR! [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/@angular'] { npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'mkdir', npm ERR! path: '/usr/local/lib/node_modules/@angular' npm ERR! } npm ERR! npm ERR! The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator. npm ERR! A complete log of this run can be found in: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_09_59_578Z-debug-0.log
К счастью, исправление было простым. Мне просто нужно было изменить команду на «sudo npm install -g @angular/cli», тем самым предоставив административные привилегии для запуска команды. Это дало следующий результат:
➜ DatingApp git:(master) sudo npm install -g @angular/cli Password: npm WARN deprecated @npmcli/[email protected]: This functionality has been moved to @npmcli/fs added 256 packages in 12s 37 packages are looking for funding run `npm fund` for details
Далее, при запуске любой команды Angular возникала пара вопросов:
? Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion will modify configuration files in your home directory.) Yes Appended `source <(ng completion script)` to `/Users/heshan/.bashrc`. Restart your terminal or run the following to autocomplete `ng` commands: source <(ng completion script) ? Would you like to share pseudonymous usage data about this project with the Angular Team at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more details and how to change this setting, see https://angular.io/analytics. Yes Thank you for sharing pseudonymous usage data. Should you change your mind, the following command will disable this feature entirely:
На первый вопрос было определенное «Да», а на второй вариант «Нет» является правдоподобным выбором, если вы предпочитаете не делиться своими данными. Убедившись в этом, я проверил версию Angular:
➜ DatingApp git:(master) ✗ ng version _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___| |___/ Angular CLI: 16.0.4 Node: 18.16.0 Package Manager: npm 9.5.1 OS: darwin x64 Angular: ... Package Version ------------------------------------------------------ @angular-devkit/architect 0.1600.4 (cli-only) @angular-devkit/core 16.0.4 (cli-only) @angular-devkit/schematics 16.0.4 (cli-only) @schematics/angular 16.0.4 (cli-only)
После подтверждения я начал создавать наше первое приложение:
➜ DatingApp git:(master) ng new client ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? CSS CREATE client/README.md (1060 bytes) CREATE client/.editorconfig (274 bytes) CREATE client/.gitignore (548 bytes) CREATE client/angular.json (2700 bytes) CREATE client/package.json (1037 bytes) CREATE client/tsconfig.json (901 bytes) CREATE client/tsconfig.app.json (263 bytes) CREATE client/tsconfig.spec.json (273 bytes) CREATE client/.vscode/extensions.json (130 bytes) CREATE client/.vscode/launch.json (470 bytes) CREATE client/.vscode/tasks.json (938 bytes) CREATE client/src/main.ts (214 bytes) CREATE client/src/favicon.ico (948 bytes) CREATE client/src/index.html (292 bytes) CREATE client/src/styles.css (80 bytes) CREATE client/src/app/app-routing.module.ts (245 bytes) CREATE client/src/app/app.module.ts (393 bytes) CREATE client/src/app/app.component.css (0 bytes) CREATE client/src/app/app.component.html (23115 bytes) CREATE client/src/app/app.component.spec.ts (991 bytes) CREATE client/src/app/app.component.ts (210 bytes) CREATE client/src/assets/.gitkeep (0 bytes) ⠦ Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: @angular/core@undefined npm ERR! node_modules/@angular/core npm ERR! @angular/core@"^16.0.0" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @angular/core@"16.0.4" from @angular/[email protected] npm ERR! node_modules/@angular/animations npm ERR! @angular/animations@"^16.0.0" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! npm ERR! For a full report see: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_13_44_797Z-eresolve-report.txt npm ERR! A complete log of this run can be found in: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_13_44_797Z-debug-0.log ✖ Package install failed, see above. The Schematic workflow failed. See above.
Однако все было не так гладко, как ожидалось. После включения маршрутизации Angular и выбора CSS для формата таблицы стилей возникла неоднозначная проблема. Согласно предложению, я попытался решить эту проблему, повторно запустив команду с флагом «—force»:
➜ DatingApp git:(master) ✗ ng new client --force ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? CSS ⠏ Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: @angular/core@undefined npm ERR! node_modules/@angular/core npm ERR! @angular/core@"^16.0.0" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @angular/core@"16.0.4" from @angular/[email protected] npm ERR! node_modules/@angular/animations npm ERR! @angular/animations@"^16.0.0" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! npm ERR! For a full report see: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_16_22_053Z-eresolve-report.txt npm ERR! A complete log of this run can be found in: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_16_22_053Z-debug-0.log ✖ Package install failed, see above. The Schematic workflow failed. See above.
Однако это не устранило проблему. Подозревая, что виновато мое интернет-соединение, я решил настроить максимальное время ожидания:
➜ DatingApp git:(master) ✗ npm config set fetch-retry-maxtimeout 120000 ➜ DatingApp git:(master) ✗ npm cache clean --force npm WARN using --force Recommended protections disabled. npm ERR! code EACCES npm ERR! syscall rmdir npm ERR! path /Users/heshan/.npm/_cacache/index-v5/02/41 npm ERR! errno -13 npm ERR! npm ERR! Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which has since been addressed. npm ERR! npm ERR! To permanently fix this problem, please run: npm ERR! sudo chown -R 501:20 "/Users/heshan/.npm" npm ERR! A complete log of this run can be found in: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_25_43_955Z-debug-0.log
Перед пересозданием приложения мне пришлось очистить кеш:
➜ DatingApp git:(master) ✗ npm cache clean --force npm WARN using --force Recommended protections disabled. npm ERR! code EACCES npm ERR! syscall rmdir npm ERR! path /Users/heshan/.npm/_cacache/index-v5/02/41 npm ERR! errno -13 npm ERR! npm ERR! Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which has since been addressed. npm ERR! npm ERR! To permanently fix this problem, please run: npm ERR! sudo chown -R 501:20 "/Users/heshan/.npm" npm ERR! A complete log of this run can be found in: npm ERR! /Users/heshan/.npm/_logs/2023-06-05T02_25_43_955Z-debug-0.log
Столкнувшись с проблемой доступа, я прибегнул к «sudo», чтобы еще раз очистить кеш:
➜ DatingApp git:(master) ✗ sudo npm cache clean --force Password: npm WARN using --force Recommended protections disabled.
Сделав это, я удалил папку «клиент» и снова попытался создать приложение:
➜ DatingApp git:(master) ✗ rm -rf client ➜ DatingApp git:(master) ng new client --force ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? CSS CREATE client/README.md (1060 bytes) CREATE client/.editorconfig (274 bytes) CREATE client/.gitignore (548 bytes) CREATE client/angular.json (2700 bytes) CREATE client/package.json (1037 bytes) CREATE client/tsconfig.json (901 bytes) CREATE client/tsconfig.app.json (263 bytes) CREATE client/tsconfig.spec.json (273 bytes) CREATE client/.vscode/extensions.json (130 bytes) CREATE client/.vscode/launch.json (470 bytes) CREATE client/.vscode/tasks.json (938 bytes) CREATE client/src/main.ts (214 bytes) CREATE client/src/favicon.ico (948 bytes) CREATE client/src/index.html (292 bytes) CREATE client/src/styles.css (80 bytes) CREATE client/src/app/app-routing.module.ts (245 bytes) CREATE client/src/app/app.module.ts (393 bytes) CREATE client/src/app/app.component.css (0 bytes) CREATE client/src/app/app.component.html (23115 bytes) CREATE client/src/app/app.component.spec.ts (991 bytes) CREATE client/src/app/app.component.ts (210 bytes) CREATE client/src/assets/.gitkeep (0 bytes) ✔ Packages installed successfully. Directory is already under version control. Skipping initialization of git.
На этот раз создание приложения прошло успешно. Наполненный предвкушением, я попытался запустить сервер Angular:
➜ DatingApp git:(master) ✗ cd client ➜ client git:(master) ✗ ng serve ? Would you like to share pseudonymous usage data about this project with the Angular Team at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more details and how to change this setting, see https://angular.io/analytics. No Global setting: enabled Local setting: disabled Effective status: disabled ✔ Browser application bundle generation complete. Initial Chunk Files | Names | Raw Size vendor.js | vendor | 2.26 MB | polyfills.js | polyfills | 328.93 kB | styles.css, styles.js | styles | 226.36 kB | main.js | main | 48.09 kB | runtime.js | runtime | 6.51 kB | | Initial Total | 2.86 MB Build at: 2023-06-05T03:04:24.623Z - Hash: a8cfd866df97a464 - Time: 26081ms ** Angular Live Development Server is listening on localhost:4200, open your browser on https://localhost:4200/ ** ✔ Compiled successfully.
После успешной сборки и компиляции сервер Angular заработал. К моему удовольствию, я наконец-то смог просмотреть приложение на https://localhost:4200/.
В заключение, мой первоначальный набег на Angular имел немало проблем. Однако благодаря настойчивости и устранению неполадок я смог преодолеть эти препятствия, что дало мне глубокое чувство выполненного долга и богатство новых знаний. Я надеюсь, что мой рассказ поможет другим, кто отправляется в подобное путешествие в царство Angular.