Angular 框架入门教程:从安装到路由、服务与状态管理详解

news2024/10/25 1:17:45

一、引言

在前端开发领域,Angular 是一个强大且流行的框架。它由 Google 维护,基于 TypeScript,采用模块化设计,提供了组件化开发、依赖注入、路由、表单处理等丰富功能,旨在帮助开发者构建高效、可维护的单页应用程序(SPA),提升开发效率和用户体验。

二、安装 Angular

  1. 安装 Node.js 和 npm:Angular 依赖 Node.js 和 npm 运行。从 Node.js 官方网站下载并安装它们。
  2. 安装 Angular CLI:使用命令npm install -g @angular/cli安装 Angular CLI,安装完成后可用ng --version检查版本。

三、创建 Angular 项目

  1. 使用 Angular CLI 创建项目:ng new my-app,Angular CLI 会自动创建项目结构并安装依赖项。
  2. 运行项目:进入项目目录,执行cd my-app后再运行ng serve,开发服务器启动后可在浏览器中通过http://localhost:4200访问应用程序。

四、Angular 项目结构

1.项目目录结构

  1. e2e/:端到端测试目录。
  2. node_modules/:项目依赖的第三方模块。
  3. src/:项目源代码目录。
  4. .angular-cli.json:Angular CLI 的配置文件。
  5. package.json:项目的包管理文件。
  6. tsconfig.json:TypeScript 的配置文件。

2.主要文件介绍

  1. app.module.ts:定义应用程序的模块。
  2. app.component.ts:定义应用程序的根组件。
  3. index.html:应用程序的入口文件。
  4. main.ts:应用程序的启动文件。

五、Angular 组件

1.组件概念

  • 组件是包含 HTML 模板、TypeScript 代码和 CSS 样式的独立单元,负责显示数据、处理用户输入和与其他组件交互。

2.创建组件

  • 使用ng generate component my-component可创建新组件,Angular CLI 会在src/app/下创建包含模板、代码和样式文件的文件夹。

3.组件模板

  • 定义组件外观和布局,可使用 Angular 的模板语法显示数据、绑定事件和使用指令。例如:
<div>
  <h1>{{title}}</h1>
  <p>{{description}}</p>
  <button (click)="onClick()">Click me</button>
</div>

4.组件类

用 TypeScript 文件定义组件行为和逻辑,可定义属性、方法和生命周期钩子。例如:

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  title = 'My Component';
  description = 'This is my component.';

  onClick() {
    console.log('Button clicked!');
  }
}

六、Angular 模块

  1. 模块概念:在 Angular 中,模块是组织代码的方式,将相关组件、服务、指令等组合在一起,形成独立功能单元,提高代码可维护性和可扩展性,方便复用。
    • declarations:声明模块中包含的组件、指令和管道。
    • imports:导入其他模块以使用其中功能。
    • providers:提供服务,可在模块中的组件注入使用。
    • exports:导出模块中的部分内容供其他模块使用。
  2. 模块代码示例:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my-component/my-component.component';

@NgModule({
  declarations: [MyComponent],
  imports: [
    CommonModule
  ],
  exports: [MyComponent]
})
export class MyModule { }

七、Angular 路由配置方法

1.路由概念

  • 路由是 Angular 应用程序的导航机制,定义不同 URL 路径和对应的组件,让用户通过 URL 访问不同页面。

2.配置路由

  • 使用RouterModule.forRoot()方法配置路由。例如:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

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

3.路由参数

  • 可在路由中定义参数,在组件中通过注入ActivatedRoute服务获取参数值。例如:
const routes: Routes = [
  { path: 'user/:id', component: UserComponent }
];

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe(params => {
      const id = params['id'];
      console.log(id);
    });
  }
}

4.路由导航守卫

  • 可控制用户导航行为,如在用户未登录时阻止访问某些页面。Angular 提供多种导航守卫,如CanActivateCanActivateChildCanDeactivate等。例如:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    if (isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}
  • 在路由配置中使用导航守卫
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];

5.懒加载模块

  • 对于大型应用程序,可使用懒加载模块提高性能,只有在用户访问特定路由时才加载模块。
  • 创建懒加载模块:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LazyComponent } from './lazy.component';

const routes: Routes = [
  { path: '', component: LazyComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  declarations: [LazyComponent]
})
export class LazyModule { }
  • 在主路由配置中使用懒加载模块:
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'lazy', loadChildren: () => import('./lazy.module').then(m => m.LazyModule) }
];

八、Angular 服务

1.服务概念

  • 服务是可复用代码块,可封装业务逻辑、数据访问等通用功能,在不同组件间共享。

2.创建服务

  • 使用ng generate service my-service创建服务,Angular CLI 会在src/app/下创建服务的 TypeScript 文件。

3.注入服务

  • 在组件中通过依赖注入获取服务实例。例如:
import { Component } from '@angular/core';
import { MyService } from './my-service.service';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  constructor(private myService: MyService) { }
}

4.使用服务

  • 服务可提供数据存储、网络请求等功能。例如:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  private data: string[] = [];

  addData(item: string) {
    this.data.push(item);
  }

  getData() {
    return this.data;
  }
}
  • 在组件中使用服务:
import { Component } from '@angular/core';
import { MyService } from './my-service.service';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  constructor(private myService: MyService) { }

  addItem() {
    const newItem = 'New item';
    this.myService.addData(newItem);
    console.log(this.myService.getData());
  }
}

九、Angular 表单处理

1.模板驱动表单

  • 通过在模板中使用表单指令实现表单验证和提交。例如:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <input type="text" name="username" ngModel required>
  <input type="password" name="password" ngModel required>
  <button type="submit">Submit</button>
</form>
  • 在组件中处理表单提交:
import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  onSubmit(form: any) {
    if (form.valid) {
      console.log(form.value);
    } else {
      console.log('Form is invalid');
    }
  }
}

2.响应式表单

  • 在组件类中创建表单模型实现表单验证和提交。例如:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  myForm = new FormGroup({
    username: new FormControl('', Validators.required),
    password: new FormControl('', Validators.required)
  });

  onSubmit() {
    if (this.myForm.valid) {
      console.log(this.myForm.value);
    } else {
      console.log('Form is invalid');
    }
  }
}
  • 在模板中绑定表单模型:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <input type="text" formControlName="username">
  <input type="password" formControlName="password">
  <button type="submit">Submit</button>
</form>

十、Angular 状态管理

1.状态管理概念

  • 在复杂应用程序中,多个组件可能需要共享和同步数据状态,状态管理用于管理应用程序状态,确保数据一致性和可维护性。

2.NgRx 状态管理库

  • NgRx 是流行的 Angular 状态管理库,基于 Redux 理念,提供可预测、可维护的方式管理应用程序状态,包含actions(定义动作)、reducers(根据动作更新状态)、effects(处理异步操作并触发动作)、selectors(从状态中选择特定数据)。例如:
  • 定义状态模型:
export interface AppState {
  counter: number;
}

export const initialState: AppState = {
  counter: 0
};
  • 定义动作:
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

export class IncrementAction implements Action {
  readonly type = INCREMENT;
}

export class DecrementAction implements Action {
  readonly type = DECREMENT;
}
  • 定义 reducer:
import { AppState, initialState } from './app.state';
import { INCREMENT, DECREMENT } from './app.actions';

export function reducer(state = initialState, action: any): AppState {
  switch (action.type) {
    case INCREMENT:
      return {...state, counter: state.counter + 1 };
    case DECREMENT:
      return {...state, counter: state.counter - 1 };
    default:
      return state;
  }
}
  • 在模块中配置 NgRx:
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { reducer } from './app.reducer';

@NgModule({
  imports: [
    StoreModule.forRoot({ appState: reducer })
  ]
})
export class AppModule { }

十一、总结

本文介绍了 Angular 框架的基本概念、安装和使用方法,包括项目结构、组件、模块、路由配置、服务、表单处理和状态管理等方面。通过学习本文,可对 Angular 框架有初步了解,并能使用 Angular CLI 创建、开发和维护 Angular 应用程序。Angular 是功能强大的前端框架,若想深入学习,可参考 Angular 的官方文档和其他相关资源。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2222847.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Leetcode 最长公共前缀

java solution class Solution {public String longestCommonPrefix(String[] strs) {if(strs null || strs.length 0) {return "";}//用第一个字符串作为模板,利用indexOf()方法匹配,由右至左逐渐缩短第一个字符串的长度String prefix strs[0];for(int i 1; i …

【Java】反射概述与详解

目录 引言 一、概述 二、获取Class对象 三、反射获取构造方法 代码示例&#xff1a; 四、反射获取成员变量 代码示例&#xff1a; 五、反射获取成员方法 代码示例&#xff1a; 结语 引言 Java中的反射&#xff08;Reflection&#xff09;是一种强大的机制&#…

热门的四款PDF合并工具大比拼!!!

在现代的数字化办公环境中&#xff0c;PDF文件已经成为了一种重要的文件格式&#xff0c;用于保存和共享各种类型的文档。然而&#xff0c;有时候我们需要将多个PDF文件合并成一个文件&#xff0c;这时候就离不开好用的PDF合并工具了。选择一个好的PDF合并工具是一个长期的投资…

Python基于OpenCV的实时疲劳检测

2.检测方法 1&#xff09;方法 与用于计算眨眼的传统图像处理方法不同&#xff0c;该方法通常涉及以下几种组合&#xff1a; 1、眼睛定位。 2、阈值找到眼睛的白色。 3、确定眼睛的“白色”区域是否消失了一段时间&#xff08;表示眨眼&#xff09;。 相反&#xff0c;眼睛长…

【Power Query】List.Select 筛选列表

List.Select 筛选列表 ——在列表中返回满足条件的元素 List.Select(列表,判断条件) 不是列表的可以转成列表再筛选&#xff0c;例如 Record.ToList 不同场景的判断条件参考写法 (1)单条件筛选 列表中小于50的数字 List.Select({1,99,8,98,5},each _<50) (2)多条件筛…

红黑树(Java数据结构)

前言&#xff1a; 红黑树的学习需要大家对二叉搜索树与AVL树有深刻的理解&#xff0c;如果话没有看过我对二叉搜索树与AVL树的讲解的铁子们可以先看看上一篇文章&#xff1a;二叉搜索树与AVL树(java数据结构)-CSDN博客 红黑树&#xff1a; 什么是红黑树&#xff1f; 红黑树&a…

CenterTrack算法详解

背景&#xff1a; 早期追踪器在缺乏强的低水平线索下&#xff0c;容易失败检测后跟踪的模型依赖于检测器&#xff0c;且需要一个单独的阶段匹配关联策略的时间长 简介&#xff1a; 基于点的跟踪思想&#xff0c;通过预测目标的中心点来进行跟踪&#xff0c;同时实现检测与跟…

LLM在Reranker任务上的最佳实践?A simple experiment report(with code)

知乎&#xff1a;车中草同学(已授权)链接&#xff1a;https://zhuanlan.zhihu.com/p/987727357 引言 在BERT时代&#xff0c;对于Reranker任务&#xff0c;我们使用encoder-only的BERT为基座&#xff0c;拼接query和doc输入到BERT中去&#xff0c;在使用CLS的向量通过一个MLP&a…

身份证识别JAVA+OPENCV+OCR

一、相关的地址 https://github.com/tesseract-ocr/tessdata Releases - OpenCV opencv要装好&#xff0c;我装的是4.5.3的&#xff0c;最新版的没试过。 tessdata就下载了需要用的。好像还有best和fast的版本&#xff0c;我试了一下报错&#xff0c;不知道是不是版本不支持…

华为配置 之 远程管理配置

目录 简介&#xff1a; 知识点&#xff1a; Telnet远程管理 &#xff08;1&#xff09;配置接口IP并确保R1和R2处于同一个网段 &#xff08;2&#xff09;使用password认证模式远程登录 &#xff08;3&#xff09;使用AAA认证模式远程登录 SSH远程管理 &#xff08;1&a…

基于springboot的网上服装商城推荐系统的设计与实现

基于springboot的网上服装商城推荐系统的设计与实现 开发语言&#xff1a;Java 框架&#xff1a;springboot JDK版本&#xff1a;JDK1.8 服务器&#xff1a;tomcat7 数据库&#xff1a;mysql 5.7 数据库工具&#xff1a;Navicat11 开发软件&#xff1a;idea 源码获取&#xf…

【deathStarBench】2.安装k8s集群

安装docker 通过以下命令安装docker&#xff1a; sudo yum install docker-ce-26.1.4 docker-ce-cli-26.1.4 containerd.io随后通过查看docker --version&#xff0c;可以确定是否安装的版本一样 启动docker systemctl start docker && systemctl enable docker.se…

《纳瓦尔宝典:财富和幸福指南》读书随笔

最近在罗胖的得到听书中听到一本书&#xff0c;感觉很有启发&#xff0c;书的名字叫《纳瓦尔宝典》&#xff0c;从书名上看给人的感觉应该财富知识类、鸡汤爆棚哪类。纳瓦尔&#xff0c;这个名字之前确实没有听说过&#xff0c;用一句话介绍一下&#xff0c;一个印度裔的硅谷中…

【LeetCode】修炼之路-0006-Zigzag Conversion (Z 字形变换)【python】

题目 The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: “PAHNAPLSIIGYIR” …

荣耀电脑管家-系统重装之查询设备序列号

winr输入cmd&#xff0c;再命令行中输入 wmic bios get serialnumber 如下所示

代码随想录算法训练营第六天|454四数相加II、 383赎金信、15三数之和、18四数之和

day06 1. 454四数相加II 首先定义 一个unordered_map&#xff0c;key放a和b两数之和&#xff0c;value 放a和b两数之和出现的次数。遍历大A和大B数组&#xff0c;统计两个数组元素之和&#xff0c;和出现的次数&#xff0c;放到map中。定义int变量count&#xff0c;用来统计 …

YAML格式校验API:免费工具的使用指南

YAML&#xff08;YAML Ain’t Markup Language&#xff09;是一种人类可读的数据序列化格式&#xff0c;广泛用于配置文件、数据交换等场景。由于其简洁的语法和良好的可读性&#xff0c;YAML 在开发和运维领域中越来越受到欢迎。然而&#xff0c;在使用 YAML 时&#xff0c;格…

Xcode文件默认存储位置-使用c++file保存文件默认路径以及设置为路径为当前项目路径

Xcode文件默认存储位置-使用cfile保存文件默认路径以及设置为路径为当前项目路径 1.概述 使用Xcode工具开发时候&#xff0c;遇到C调用file创建文件后&#xff0c;在当前项目中找不到文件路径。这是由于xcode会将文件保存到默认设置的路径。下面是查看文件默认存储路径和修改…

数组中的算法

目录 1.什么是数组 2.数组上的算法 2.1二分查找算法 什么是二分查找算法&#xff1f; 算法步骤 算法时间复杂度 一个问题 例题 题目分析 解题代码 2.2双指针法 什么是双指针法&#xff1f; 例题 题目分析 解题代码 1.什么是数组 数组是在一块连续的内存空间…

C++,STL 047(24.10.24)

内容 对set容器的元素进行查找与统计。 运行代码 #include <iostream> #include <set>using namespace std;void printSet(set<int> &s) {for (set<int>::iterator it s.begin(); it ! s.end(); it){cout << *it << " ";…