Angular完全指南:从安装到高级应用(RHEL 8环境)

云信安装大师
90
AI 质量分
10 5 月, 2025
7 分钟阅读
0 阅读

Angular完全指南:从安装到高级应用(RHEL 8环境)

引言

Angular是一个强大的前端框架,由Google维护,特别适合构建复杂的单页应用程序(SPA)。本指南将带你在RHEL 8系统上完成从Angular环境搭建到高级应用的完整流程。

准备工作

系统要求

  • RHEL 8操作系统
  • 至少4GB内存(推荐8GB)
  • 20GB可用磁盘空间
  • 稳定的网络连接

前置知识

  • 基本的Linux命令行操作
  • JavaScript基础知识
  • TypeScript基础(非必需但推荐)

第1部分:环境搭建

1.1 安装Node.js和npm

Angular需要Node.js运行时环境。我们将使用NodeSource仓库安装最新LTS版本:

代码片段
# 添加NodeSource仓库
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -

# 安装Node.js和npm
sudo dnf install -y nodejs

# 验证安装
node --version
npm --version

注意事项
– RHEL默认仓库中的Node.js版本通常较旧,建议使用NodeSource仓库
– 如果遇到权限问题,可以添加--unsafe-perm参数

1.2 安装Angular CLI

Angular CLI是官方提供的命令行工具,用于创建和管理Angular项目:

代码片段
# 全局安装Angular CLI
sudo npm install -g @angular/cli

# 验证安装
ng version

经验分享
-g表示全局安装,使ng命令在任何目录都可用
– 如果安装速度慢,可以设置淘宝镜像:npm config set registry https://registry.npm.taobao.org

第2部分:创建第一个Angular应用

2.1 初始化项目

代码片段
# 创建新项目(my-app是项目名称)
ng new my-app

# CLI会询问一些配置选项:
# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? CSS

原理说明
ng new命令会创建一个完整的项目结构,包括:
src/ – 主要源代码目录
node_modules/ – 依赖包目录
angular.json – Angular配置文件

2.2 启动开发服务器

代码片段
# 进入项目目录
cd my-app

# 启动开发服务器(默认端口4200)
ng serve --open

注意事项
--open参数会自动在浏览器中打开应用(http://localhost:4200)
– Ctrl+C可以停止服务器

第3部分:核心概念与实践

3.1 Angular组件示例

让我们创建一个简单的计数器组件:

代码片段
# CLI生成新组件(自动注册到模块)
ng generate component counter --skip-tests=true --inline-style=true --inline-template=true 

编辑生成的counter.component.ts文件:

代码片段
import { Component } from '@angular/core';

@Component({
 selector: 'app-counter',
 template: `
   <h2>计数器示例</h2>
   <button (click)="decrement()">-</button>
   <span>{{ count }}</span>
   <button (click)="increment()">+</button>
 `,
 styles: [`
   button {
     padding:   5px   15px;
     margin:   0   10px;
     font-size:   16px;
   }
 `]
})
export class CounterComponent {
 count =   0;

 increment() {
   this.count++;
 }

 decrement() {
   this.count--;
 }
}

app.component.html中使用这个组件:

代码片段
<app-counter></app-counter>

关键概念解释
装饰器(@Component):定义组件的元数据(selector、template等)
数据绑定({{ count }}):显示组件属性值
事件绑定((click)):响应用户交互

3.2 Angular服务示例

服务用于封装可复用的业务逻辑:

代码片段
ng generate service data --skip-tests=true 

编辑生成的data.service.ts文件:

代码片段
import { Injectable } from '@angular/core';

@Injectable({
 providedIn: 'root' // Angular6+推荐方式,无需在模块中注册服务  
})
export class DataService {
 private items = ['Angular', 'React', 'Vue'];

 getItems(): string[] {
   return this.items;
 }

 addItem(item: string): void {
   this.items.push(item);
 }
}

在组件中使用服务:

代码片段
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
 selector: 'app-item-list',
 template: `
   <ul>
     <li *ngFor="let item of items">{{ item }}</li>
   </ul>
 `
})
export class ItemListComponent implements OnInit {
 items: string[] = [];

 constructor(private dataService: DataService) {}

 ngOnInit() {
   this.items = this.dataService.getItems();
 }
}

RHEL特定优化与问题解决

SELinux配置调整(可选)

如果你遇到权限问题,可以调整SELinux策略:

代码片段
sudo setsebool -P httpd_can_network_connect true 

Firewall配置(生产环境)

允许HTTP端口访问:

代码片段
sudo firewall-cmd --permanent --add-port=4200/tcp 
sudo firewall-cmd --reload 

Angular高级应用技巧

Lazy Loading模块懒加载

优化大型应用的加载速度:

  1. 创建特性模块
代码片段
ng generate module admin --route admin --module app.module 
  1. 路由配置
代码片段
const routes: Routes = [
 { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];

HTTP拦截器示例

实现统一的请求处理逻辑:

代码片段
@Injectable()
export class AuthInterceptor implements HttpInterceptor {

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   // Clone请求并添加认证头  
   const authReq = req.clone({
     headers: req.headers.set('Authorization', 'Bearer token')
   });

   return next.handle(authReq);
 }
}

在模块中注册拦截器:

代码片段
@NgModule({
 providers: [
   { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
 ]
})
export class AppModule {}

Angular性能优化建议

  1. 启用生产模式构建
代码片段
ng build --prod 

这个命令会启用以下优化:
– AOT编译(提前编译模板)
– Tree-shaking移除未使用代码
– UglifyJS代码压缩

  1. 使用OnPush变更检测策略

在组件装饰器中设置变更检测策略:

代码片段
@Component({
 selector: 'app-performance',
 changeDetection: ChangeDetectionStrategy.OnPush,
 // ...
})
export class PerformanceComponent {}
  1. 启用Ivy渲染引擎

在tsconfig.json中确保启用Ivy:

代码片段
{
 "angularCompilerOptions": {
   "enableIvy": true  
 }
}

RHEL上的持续集成方案

示例Jenkinsfile配置:

代码片段
pipeline {
 agent any

 stages {

   stage('Install') {  
     steps {
       sh 'npm install'
     }
   }

   stage('Test') {
     steps {  
       sh 'npm test'
     }
   }  

   stage('Build') {  
     steps {  
       sh 'npm run build --prod'
       archiveArtifacts artifacts: 'dist/**/*'  
     }  
   }  
 }  

 post {  
    always {  
        cleanWs()  
    }  
 }   
}

RHEL系统监控建议

监控Node进程资源占用:

代码片段
sudo dnf install -y htop  

htop -p $(pgrep node)

或者使用systemd服务管理:

代码片段
[Unit]
Description=Angular App Server  

[Service]  
ExecStart=/usr/bin/ng serve --prod --port=4200    
WorkingDirectory=/var/www/my-app    
Restart=always    

[Install]    
WantedBy=multi-user.target    

Angular更新策略

安全更新检查:

代码片段
npx ng update      
npx ng update @angular/core @angular/cli     
npm audit fix     

RHEL安全加固建议

  1. 限制npm权限
代码片段
mkdir ~/.npm-global    
npm config set prefix '~/.npm-global'    
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc    
source ~/.bashrc     
chmod -R   755 ~/.npm-global     
setfacl -Rm u:$USERNAME:-wx ~/.npm-global     
  1. 定期清理缓存
代码片段
npm cache verify     
dnf clean all     
journalctl --vacuum-time=7d     
rm -rf ~/.cache/*      
find /tmp /var/tmp -atime +7 -delete      
  1. 启用SELinux保护
代码片段
semanage port -a -t http_port_t -p tcp   4200      
restorecon -Rv /opt/my-app      
chcon system_u object_r httpd_sys_content_t /opt/my-app/dist/    
setsebool httpd_can_network_connect on    
getenforce      
  1. 防火墙规则细化
代码片段
firewall-cmd --permanent --zone=public \
--add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port port="4200" protocol="tcp" accept'    

firewall-cmd --reload      
firewall-cmd --list-all       
iptables-save > /etc/sysconfig/iptables.backup       
systemctl restart firewalld.service        
  1. 系统资源限制

编辑/etc/security/limits.conf:

代码片段
* soft nofile   8192    
* hard nofile   20000   
nodeuser soft nproc   4096   
nodeuser hard nproc   8192   

然后重新登录生效。监控日志:

代码片段
journalctl _SYSTEMD_UNIT=myapp.service -f     
tailf /var/log/messages | grep node      
sar -u   5   10 > cpu.log &     
vmstat   5 > mem.log &        
lsof +D /opt/my-app | wc -l        
ss -tulnp | grep node        
netstat plant | grep node        
ps aux | grep node | sort k4nr | head       
free mh && uptime && df hT && top bn1 | head n20      
du shx /opt/my-app/* | sort hr | head n10       
find /opt/my-app type f perm o+w exec ls l {} +         
rpm Va > rpm_verify.log        
ausearch ts today m ADD_PACKAGE m EXECVE f su root m yes > audit.log         
sealert a > selinux_alerts.log       
tunedadm active && tunedadm recommend        
sestatus b && getenforce && semanage boolean list l && semanage port list l          
firewall cmd list all zones verbose permanent no pager | less S          
systemctl list timers all no pager | grep angular          
lastb root | head n20 && last root | head n20           
cat /var/log/secure* | grep fail | wc l            
chkrootkit q || rkhunter c skip keypresses || lynis audit system            
clamscan ri /opt/my app log=/var/log/clamav scan.log move=/var/quarantine           
freshclam v update db && clamdscan reload            
certbot renew dry run post hook systemctl restart myapp.service            
logrotate force /etc/logrotate.d/angular || echo "*/30 * * * * root logrotate f /etc/logrotate.d/angular" >> /etc/crontab             
alternatives config java || alternatives display java || update alternatives config java              
sysctl a grep fs.inotify || echo fs.inotify.max user watches=524288 >> /etc/sysctl.conf sysctl p             
ldconfig p v grep libnode || echo "/usr/local/lib64/node modules" >> /etc/ld.so.conf.d/node.conf ldconfig v              
getfacl Rpn /opt/my app > permissions backup.acl && setfacl Rb permissions backup.acl             
crontab l u nodeuser || echo "* * * * * cd /opt/my app && npm run healthcheck > healthcheck.log        "             

## Node.js进程管理最佳实践  

对于生产环境推荐使用PM2进行进程管理:

1\.首先全局安装PM2:
``````bash     
sudo npm install pm2@latest g         
sudo pm2 startup systemd #生成systemd服务脚本           
``

2.创建PM2生态系统文件ecosystem.config.js:

代码片段
module.exports = {       
 apps : [{        
 name : "my angular ssr", #应用名称         
 script : "node", #解释器路径         
 args : "dist/server/main.js", #入口文件路径         
 instances : "max", #根据CPU核心数启动实例数         
 exec mode : "cluster", #集群模式         
 watch : false, #禁用文件监视          
 env production : {           
 NODE ENV:"production",           
 PORT:"4000",           
 STATIC PATH:"dist/browser"          
 },          
 error file : "/var/log/pm2/app err.log", #错误日志路径          
 out file : "/var/log/pm2/app out.log", #输出日志路径          
 merge logs : true, #合并日志          
 log date format:"YYYY MM DD HH:mm Z" #日志时间格式          
 }]        
};         

3.常用PM2命令:
“““bash
pm2 start ecosystem.config.js production #启动应用集群
pm2 save #保存当前进程列表
pm2 resurrect #恢复保存的进程列表
pm2 monit #监控所有进程状态
pm2 logs tail n100 err out combined timestamp #查看最新100行日志
pm2 reload all gracefulReload #优雅重载所有进程(零停机)
pm2 scale my angular ssr +4 #动态扩展4个工作进程
pm2 updatePM2 #更新PM自身到最新版本
pm2 deploy ecosystem.config.js production setup #首次部署初始化
pm deploy ecosystem.config.js production update rolling restart interval=”1000″ parallel=”false” post deploy=”nginx reload” pre deploy setup remote commands pull origin master yarn install ng build prod” wait ready timeout=”5000″ max retries=”3″ min uptime=”30000″” path=”/var/www/releases/%Y%m%d%H%M%S”” user=”deployer”” host=[“192 .168 .1 .100″]”” ref HEAD origin/master”” repo git@github.com user repo.git”” ssh options StrictHostKeyChecking no PasswordAuthentication no”” pre local setup yarn global add @angular/cli typescript pm serve dist browser port $PORT disableHostCheck true proxyConfig proxy.conf.json”” post setup ln sfn current releases/%Y%m%d%H%M%S”” keep releases last five delete others true symlink current releases/%Y%m%d%H%M%S”””

对于更复杂的部署场景可以考虑容器化方案(Docker + Kubernetes):

Dockerfile示例(多阶段构建):

FROM node AS builder

WORKDIR/app COPY package.json yarn.lock ./ RUN yarn install COPY . . RUN yarn build prod

FROM nginx alpine AS runtime

COPY from builder app/dist/browser usr/share/nginx/html COPY nginx.conf etc/nginx/conf.d/default.conf EXPOSE 80 CMD [“nginx”,”g”,”daemon off;”]

nginx.conf参考配置(SSR场景):

server listen 80; server name localhost; location static alias usr/share/nginx/html; expires max; add header Cache Control public; gzip on; gzip types text plain text css application javascript application json application wasm image svg+xml font woff font woff application font ttf; brotli on; brotli types text plain text css application javascript application json application wasm image svg+xml font woff font woff application font ttf; location proxy pass http://localhost 4000; proxy set header Host $host; proxy set header X Real IP $remote addr; proxy set header X Forwarded For $proxy add x forwarded for; proxy set header X Forwarded Proto $scheme; proxy buffer size 128k; proxy buffers 4 256k; proxy busy buffers size 256k; client max body size 100M; keepalive timeout 65s; sendfile on; tcp nopush on; tcp nodelay on;}

原创 高质量