Angular 英雄之旅

梁丘伟
2023-12-01

Angular 英雄之旅

https://angular.cn/tutorial/toh-pt0

在组件中ts中直接定义 title 效果等于 data 展示 {{title}}

双向绑定 FormsModule

[(ngModel)]=“title”
需要在 app.module.ts 自行添加 import { FormsModule } from ‘@angular/forms’

模拟mock

export const HEROES: Hero[]=[]

渲染数组

*ngFor= ‘let item of items’

click 事件绑定

(click) = "onSelect(hero)### *ngIf 隐藏空白内容

@Input() 向 组件中输入数据

import {Input} from ‘@angular/core’;
添加 @Input 装饰器 的属性
在hmtl中正常使用 * *ngIf=“属性名” 判断是否有值展示

location

import {Location} from ‘@angular/common’
this.location.back() // 后退,返回

[hero]=“selectedHero”

单向的数据绑定 从 HeroesComponent 的 selectedHero 属性绑定到目标元素的 hero 属性,并映射到了 HeroDetailComponent 的 hero 属性。

服务

组件只关注数据的展示 所有的数据处理 获取应该交给service来做
组件 引入服务层 要在构造函数里注册

创建服务

ng generate service hero
@Injectable
这个新的服务导入了 Angular 的 Injectable 符号,并且给这个服务类添加了 @Injectable() 装饰器。 它把这个类标记为依赖注入系统的参与者之一。HeroService 类将会提供一个可注入的服务,并且它还可以拥有自己的待注入的依赖。
@Injectable({
providedIn: ‘root’,
})
用根注入器将你的服务注册成为提供者

Observable 可观察的数据

import { Observable, of } from ‘rxjs’;
做异步操作 等待Observable发出数据 然后 subscribe() 把数组传给这个回调函数

路由

ng generate module app-routing --flat --module=app
或创建项目的时候直接选择
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})

路由跳转

routerLink ="/path"

路由出口

routes

{path:’’,component:componentName}

路由传参 ‘path/:参数’

接收参数
import {ActivatedRoute } from ‘@angular/router’
this.route.snapshot.paramMap.get(‘参数名’)

默认路由

{path:’’,redirectTo:’/path’,pathMatch:‘full’},

组件

每组件都必须且只能声明在一个 NgModule 中
使用组件
ng generate component name
使用命令在需要生成组件的地方创建 自动生成 以及导入

管道操作符 |

{{hero.name | uppercase}} Details

绑定表达式中的 uppercase 位于管道操作符( | )的右边,用来调用内置管道 UppercasePipe。

HTTP 服务

在 app.module.ts 中引入
import { HttpClientModule } from ‘@angular/common/http’;
imports: [
HttpClientModule,
],

import { HttpClient, HttpHeaders } from ‘@angular/common/http’;
this.http.get(url,)

Simulate a data server

模拟远程数据服务器通讯
npm install angular-in-memory-web-api --save

// The HttpClientInMemoryWebApiModule module intercepts HTTP requests
// and returns simulated server responses.
// Remove it when a real server is ready to receive requests.
HttpClientInMemoryWebApiModule.forRoot(
InMemoryDataService, { dataEncapsulation: false }
)

模拟数据存储
ng generate service InMemoryData

 类似资料: