component
组件

service
服务,处理请求数据,解决DRY,
类似于Vuex

Exercise
- npm i
- npm install bootstrap@4.0.0-alpha.6 tether jquery --save
- 进入package.json将版本号前的
^去掉 - 创建component
ng g c - router
import { RouterModule,Routes } from '@angular/router';
const Routes: Routes = [
{
path:'',component:class类名
}
]
@ngModule({
imports:[
RouterModule.forRoot(Routes)
]
})
app.component.html中
<router-outlet></router-outlet>
以及<a routerLink='component名'></a>
在navbar.component.html中设置routerlink实现点击跳转

- service
创建serviceng g s service/user
在app.module.ts中引入
import { UserService } from './services/user.service';
@ngModule({
providers: [
UserService,
]
})
- http
在user.service.ts下引入http进行数据获取
import { Http } from '@angular/http';
在constructor中声明http
constructor(
public http:Http
) { }
- 数据获取,观察者,需要引入
rxjs
import { map } from 'rxjs/operators';
将获取的数据转成json返回
getUser(){
return this.http.get("http://localhost:3000/users" )
.map(res => res.json())
}
- subscribe ,获取api获得到的数据
先引入UserService,然后在ngOnInit中获取数据,在页面进入就获到数据。
import { UserService } from '../../services/user.service'
users:any[];
constructor(
public userService:UserService
) { }
ngOnInit(){
this.userService.getUsers()
.subscribe(users => this.users = users)
}
- 判断用户信息是否存在,如果不存在提示noUser
首先用*ngIF进行判断
ngIf then 和 else 模板
then 模板除非绑定到不同的值,否则默认是 ngIf 指- 令关联的内联模板。
else 模板除非绑定对应的值,否则默认是 null。
<table *ngIf="users?.length>0;else noUsers"></table>
使用模板参考变量#noUsers
<ng-template #noUsers>
<hr>
<h5>系统中还没有任何用户</h5>
</ng-template>
- form
在app.module.ts中引入import { FormsModule } from '@angular/forms';
<div class="form-group">
<label for="balance">收支</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.balance"
name="balance"
[disabled]="disableBalanceOnAdd"
/>
</div>
[(ngModel)]数据绑定
[diasbled]控制是否禁用
export interface User{
id?:number;
name?:string;
email?:string;
phone?:string;
balance?:number;
}
?:用于定义的时候可写可不写某一个属性
- form表单提交,
#f="ngForm"可以获取表单数据
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<div class="form-group">
<label for="name">姓名</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.name"
name="name"
minlength="2"
required
/>
</div>
onSubmit传递的参数有两个,value值为ngForm的表单数据,valid与required配合使用,用来进行数据验证。
minlength用于限制输入值的长度
在add-user.component.ts中写onSubmit函数
onSubmit({value,valid}:{value:User,valid:boolean}){
// console.log(value);
if (!valid) {
// console.log("验证失败");
}else{
// console.log("验证成功!");
})
}
}
- 路由指定相对路线
如果验证成功,跳转到指定的首页,用this.router.navigate进行跳转
this.router.navigate(['/'], { relativeTo: this.route });
该对象的relativeTo属性设置ActivatedRoute为this.route。
- routerLink 属性绑定带参数跳转
在app.module.ts中跳转到指定用户详情页路由设置
{path:"user/:id",component:UserDetailComponent},
在users.component.ts中通过拼接方式改变id的值
需要属性绑定routerLink
<td><a [routerLink]="['/hero', hero.id]"></a></td>
- 获取路由参数id
需要在user-detail.component.ts中引入ActivatedRoute和Params
import { RActivatedRoute,Params } from '@angular/router';
在constructor中定义声明ActivatedRoute
constructor(
public route:ActivatedRoute,
) { }
获取参数id
this.id = this.route.snapshot.params["id"];
扩展:
$ 是一个命名惯例,用来表明hero$是一个 Observable,而不是数组。 *ngFor 不能直接使用 Observable。
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
在ngOnInit()方法中,使用ActivatedRoute服务检索路由id的参数,从参数中提取数据,然后检索要显示的数据。
- 登录引导-路由守卫
CanActivate
需要新建一个auth.guard.ts文件,引入以下
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { map } from "rxjs";
继承CanActivate
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
public afAuth:AngularFireAuth,
public router:Router
) { }
//实现canActivate方法,返回类型为Boolean
canActivate():Observable<boolean>{
return this.afAuth.authState.map(auth =>{
if (!auth) {
this.router.navigate(["/login"]);
return false;
}else {
return true;
}
})
}
}
在app.module.ts中进行路由守卫设置
const appRoutes:Routes = [
{path:"",component:HomeComponent,canActivate:[AuthGuard]},
{path:"login",component:LoginComponent},
{path:"register",component:RegisterComponent,canActivate:[RegisterGuard]},
{path:"add-user",component:AddUserComponent,canActivate:[AuthGuard]},
{path:"user/:id",component:UserDetailComponent,canActivate:[AuthGuard]},
{path:"edit-user/:id",component:EditUserComponent,canActivate:[AuthGuard]},
{path:"settings",component:SettingsComponent,canActivate:[AuthGuard]}
]
- Pipe
angular6之pipe管道
可以在html声明中显示值转换
可以传参
<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>
可以绑定属性值
template: `
<p>The hero's birthday is {{ birthday | date:format }}</p>
<button (click)="toggleFormat()">Toggle Format</button>
`
export class HeroBirthday2Component {
birthday = new Date(1988, 3, 15); // April 15, 1988
toggle = true; // start with true == shortDate
get format() { return this.toggle ? 'shortDate' : 'fullDate'; }
toggleFormat() { this.toggle = !this.toggle; }
}
本文深入探讨了Angular框架中的核心概念——路由与组件,详细介绍了如何创建组件和服务,配置路由,以及实现表单数据绑定。文章还讲解了如何利用Angular的特性进行数据验证和跳转,并介绍了路由守卫和管道等高级功能。
1772

被折叠的 条评论
为什么被折叠?



