angular12怎么用

发布时间:2021-08-23 14:17:01 作者:小新
来源:亿速云 阅读:156
# Angular 12 使用指南:从入门到实战

## 目录
1. [Angular 12 简介](#angular-12-简介)
2. [环境搭建](#环境搭建)
3. [创建第一个Angular 12项目](#创建第一个angular-12项目)
4. [核心概念解析](#核心概念解析)
5. [组件开发实战](#组件开发实战)
6. [服务与依赖注入](#服务与依赖注入)
7. [路由与导航](#路由与导航)
8. [表单处理](#表单处理)
9. [HTTP客户端](#http客户端)
10. [测试与调试](#测试与调试)
11. [构建与部署](#构建与部署)
12. [升级与迁移](#升级与迁移)

---

## Angular 12 简介

Angular 12是Google于2021年5月发布的重大版本更新,主要改进包括:

- **Ivy引擎优化**:更小的打包体积和更快的编译速度
- **严格模式增强**:默认启用严格类型检查
- **Webpack 5支持**:提升构建性能
- **组件API改进**:新增`@angular/cdk`和`@angular/material`功能
- **弃用View Engine**:全面转向Ivy编译器

> 版本特性对比:
> | 特性 | Angular 11 | Angular 12 |
> |------|-----------|-----------|
> | 编译器 | View Engine/Ivy | 仅Ivy |
> | TypeScript | 4.0 | 4.2+ |
> | Webpack | 4 | 5(可选) |

---

## 环境搭建

### 必备工具
1. **Node.js** v12.20+ (推荐LTS版本)
   ```bash
   node -v  # 验证安装
  1. npm 6+ 或 yarn
    
    npm install -g yarn
    
  2. Angular CLI
    
    npm install -g @angular/cli@12
    ng version  # 验证安装
    

可选工具


创建第一个Angular 12项目

初始化项目

ng new my-angular12-app --strict
cd my-angular12-app
ng serve --open

项目结构解析

├── src/
│   ├── app/               # 应用主模块
│   │   ├── app.component.ts
│   │   └── app.module.ts
│   ├── assets/            # 静态资源
│   ├── environments/      # 环境配置
├── angular.json           # CLI配置
├── tsconfig.json          # TypeScript配置

核心概念解析

1. 模块(NgModule)

@NgModule({
  declarations: [AppComponent],  // 组件/指令/管道
  imports: [BrowserModule],     // 依赖模块
  providers: [],               // 服务
  bootstrap: [AppComponent]     // 根组件
})
export class AppModule {}

2. 组件(Component)

@Component({
  selector: 'app-root',
  template: `<h1>{{title}}</h1>`,  // 或 templateUrl
  styles: [`h1 { color: red }`]     // 或 styleUrls
})
export class AppComponent {
  title = 'My Angular 12 App';
}

3. 数据绑定

<!-- 插值 -->
<p>{{ user.name }}</p>

<!-- 属性绑定 -->
<img [src]="heroImageUrl">

<!-- 事件绑定 -->
<button (click)="onSave()">Save</button>

<!-- 双向绑定 -->
<input [(ngModel)]="user.name">

组件开发实战

创建新组件

ng generate component product-list

组件通信

父→子:通过@Input()

// 子组件
@Input() product: Product;

// 父组件模板
<app-product [product]="selectedProduct"></app-product>

子→父:通过@Output()

// 子组件
@Output() notify = new EventEmitter();

// 父组件模板
<app-product (notify)="onNotify($event)"></app-product>

服务与依赖注入

创建服务

ng generate service data

实现服务

@Injectable({
  providedIn: 'root'  // 全局单例
})
export class DataService {
  private apiUrl = 'https://api.example.com';

  constructor(private http: HttpClient) {}

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`${this.apiUrl}/products`);
  }
}

使用服务

@Component({...})
export class ProductListComponent implements OnInit {
  products: Product[];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getProducts().subscribe(
      products => this.products = products
    );
  }
}

路由与导航

配置路由

const routes: Routes = [
  { path: '', redirectTo: '/products', pathMatch: 'full' },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductDetailComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

路由导航

<!-- 模板中使用 -->
<a routerLink="/products" routerLinkActive="active">Products</a>

<!-- 编程式导航 -->
<button (click)="goToProducts()">Go</button>
goToProducts() {
  this.router.navigate(['/products']);
}

表单处理

模板驱动表单

<form #heroForm="ngForm" (ngSubmit)="onSubmit()">
  <input name="name" [(ngModel)]="model.name" required>
  <button type="submit" [disabled]="!heroForm.form.valid">Submit</button>
</form>

响应式表单

profileForm = new FormGroup({
  firstName: new FormControl('', Validators.required),
  lastName: new FormControl('')
});

onSubmit() {
  console.log(this.profileForm.value);
}

HTTP客户端

配置HttpClient

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [HttpClientModule],
  // ...
})
export class AppModule {}

典型CRUD操作

// GET
getProducts(): Observable<Product[]> {
  return this.http.get<Product[]>(this.productsUrl);
}

// POST
addProduct(product: Product): Observable<Product> {
  return this.http.post<Product>(this.productsUrl, product);
}

测试与调试

单元测试

describe('DataService', () => {
  let service: DataService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });
    service = TestBed.inject(DataService);
    httpTestingController = TestBed.inject(HttpTestingController);
  });

  it('should get products', () => {
    const testData: Product[] = [{ id: 1, name: 'Test' }];
    
    service.getProducts().subscribe(data => {
      expect(data).toEqual(testData);
    });

    const req = httpTestingController.expectOne('api/products');
    expect(req.request.method).toEqual('GET');
    req.flush(testData);
  });
});

构建与部署

生产环境构建

ng build --prod

部署选项

  1. 静态服务器
    
    npm install -g http-server
    cd dist/my-app
    http-server
    
  2. Docker部署
    
    FROM nginx:alpine
    COPY dist/my-app /usr/share/nginx/html
    

升级与迁移

从Angular 11升级

  1. 更新全局CLI:
    
    npm uninstall -g @angular/cli
    npm install -g @angular/cli@12
    
  2. 更新项目依赖:
    
    ng update @angular/core@12 @angular/cli@12
    

常见问题解决


结语

Angular 12通过Ivy编译器的全面采用带来了显著的性能提升和开发体验改进。本指南涵盖了从环境搭建到生产部署的全流程,建议通过实际项目实践来巩固这些概念。更多高级主题如状态管理(NgRx)、服务端渲染(SSR)等,可参考官方文档进一步学习。

延伸阅读: - Angular官方文档 - Angular Update Guide - Angular Material组件库 “`

注:实际字数约3500字,完整3700字版本需要扩展每个章节的示例代码和解释说明。如需完整版本,可以具体说明需要扩展哪些部分。

推荐阅读:
  1. 怎么用vuex
  2. 怎么用redis

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular

上一篇:HTTP服务器错误的状态代码对应的意思是什么

下一篇:HTTP服务器连接不上出现的状态代码表示什么意思

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》