服务,处理请求数据,解决DRY,
类似于Vuex
^
去掉ng g c
import { RouterModule,Routes } from '@angular/router';
const Routes: Routes = [
{
path:'',component:class类名
}
]
@ngModule({
imports:[
RouterModule.forRoot(Routes)
]
})
app.component.html中
<router-outlet></router-outlet>
以及
在navbar.component.html中设置routerlink实现点击跳转
ng g s service/user
import { UserService } from './services/user.service';
@ngModule({
providers: [
UserService,
]
})
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())
}
ngOnInit
中获取数据,在页面进入就获到数据。import { UserService } from '../../services/user.service'
users:any[];
constructor(
public userService:UserService
) { }
ngOnInit(){
this.userService.getUsers()
.subscribe(users => this.users = users)
}
*ngIF
进行判断<table *ngIf="users?.length>0;else noUsers"></table>
使用模板参考变量#noUsers
<ng-template #noUsers>
<hr>
<h5>系统中还没有任何用户h5>
ng-template>
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;
}
?:
用于定义的时候可写可不写某一个属性
#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
。
{path:"user/:id",component:UserDetailComponent},
在users.component.ts中通过拼接方式改变id的值
需要属性绑定routerLink
<td><a [routerLink]="['/hero', hero.id]">a>td>
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
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]}
]
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 Formatbutton>
`
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; }
}