自学Angular5

简介

本人是2017年开始接触angular2+版本的,一路走过来也看着angular越变越好,自学的道路上也走了不少的弯路,建议在学angular的时候最好掌握一些其它必要的知识。这里写这篇文章也是想分享下我是如何学习angular的,给你们刚学习angular的同学们铺铺路,如果写的看的不明白的同学欢迎留言。

什么是Angular

Angular 是一个开发平台。它能帮你更轻松的构建 Web 应用。Angular 集声明式模板、依赖注入、端到端工具和一些最佳实践于一身,为你解决开发方面的各种挑战。Angular 为开发者提升构建 Web、手机或桌面应用的能力。(引用官网简介)
这篇文章主要讲述了我平时工作上遇到的问题。写的比较粗糙,想起什么就写什么,没有统一的规划,后续如有机会可以写一篇进阶版。

需要哪些技术?

Angular CLI

Angular CLI是一个命令行界面工具,它可以创建项目、添加文件以及执行一大堆开发任务,比如测试、打包和发布。(引用官网简介)
  1. npm install -g @angular/cli    
  2. ng new my-app --routing --style less  (--routing 带有路由模块,--style less 样式表为less)
  3. ng serve -p 4800 --aot --host 0.0.0.0 --disable-host-check true  (-p 启动端口4800 --disable-host-check true 开启端口检查 --aot aot编译)
  4. ng build --prod -nc  (--prod 成产模式 -nc chunks以模块名命名)

Angular组建

运行 ng g c index,自动在app文件下创建组建index。
@Component({
    selector: 'app-index',//选择器
    encapsulation: ViewEncapsulation.None,//Emulated 默认 Native 私有无法访问 None 不处理
    styleUrls: ['./index.component.less'],//样式表链接
    styles: ['.primary {color: red}'],
    viewProviders:[],//依赖模块
    providers:[],//依赖服务
    exportAs:'appIndex',//模块导出标识
    //templateUrl: './index.component.html',//模板链接
    template:"<div>{{msg}}</div>",
    host:{
        '[class.test]': 'true',
        '[attr.id]': ''test'',
    }
})
export class IndexComponent{
    constructor() {
    }

    @ViewChild('movieplayer') movieplayerRef:ElementRef//获取当前dom实例。

    msg:string = 'hello angular';
    clickTest(){}
    list:Array<any> = [1,2,3,4,5];
    show:boolean = true;
    word:string
    width:number = 100;
    showTest:boolean = true;

    @Output() myEvent = new EventEmitter<any>();
    @Input() myProperty;
    _my2Property
    @Input() set my2Property(val){
        this._my2Property = val;
    };
    get my2Property(){
        return this._my2Property;
    }
}复制代码

<app-index [myProperty]="{a:1}" (myEvent)="$event.stopPropagation()" #indexRef="appIndex"></app-index>复制代码

Angular模板语法

  1. []  属性绑定
  2. ()  事件绑定
  3. *ngFor  列表渲染
  4. *ngIf  条件渲染
  5. [(ngModel)]  双向绑定
  6. #xxxx  局部变量
<div 
    [title]="msg" 
    (click)="clickTest($event)" 
    [style.width.px]="width"
    [ngStyle]="{'width.%':width}"
    [ngClass]="{'class-test':showTest}"
    [class.class-test]="showTest"
    *ngFor="let li of list;let i = index;trackBy: trackById" 
    *ngIf="show">
    <input type="text" [(ngModel)]="word">
    {{word}}
</div>

<video #movieplayer></video>
<button (click)="movieplayer.play()">

<ng-template ngFor [ngForOf]="list" let-li let-i="index" let-odd="odd" [ngForTrackBy]="trackById"></ng-template>

<ng-template [ngIf]="show"></ng-template>

<div [ngSwitch]="conditionExpression">
    <template [ngSwitchCase]="case1Exp"></template>
    <template ngSwitchCase="case2LiteralString"></template>
    <template ngSwitchDefault></template>
</div>复制代码

路由与导航

  • routing.module.ts
const routes: Routes = [
    {
         path:'',
         component:IndexComponent,
         resolve:{resolve:ResolverService},
         canActivate:[AuthGuard],
         data:{},
    }
]

@NgModule({
    imports: [RouterModule.forRoot(routes,{useHash: true})],
    exports: [RouterModule]
})
export class IndexRoutingModule {
    
}复制代码
  • resolver-service.ts
@Injectable()
export class CurrentResolverService implements Resolve<any> {
    constructor(private router: Router, private userService_: UserService) {
    }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
        //1.
        return Observable.create({})
        //2.
        return new Promise((resolve, reject) => {
            setTimeout(()=> {
                resolve({})
            },2000)
        })
        //3.
        return {}
    }
}



复制代码
  • auth.guard.ts
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

    constructor() {

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        //1.
        return Observable.create(false)
        //2.
        return new Promise((resolve, reject) => {
            setTimeout(()=> {
                resolve(false)
            },2000)
        })
        //3.
        return false
    }

    //子路由守护
    canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.canActivate(childRoute, state);
    }

    //异步加载组件
    canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
        return null;
    }
}复制代码
  • 位置标记
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>复制代码
  • 路由跳转
<a routerLink="/path" [routerLinkActive]="'active'">
<a [routerLink]="[ '/path', routeParam ]">
<a [routerLink]="[ '/path', { matrixParam: 'value' } ]">
<a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }">
<a [routerLink]="[ '/path' ]" fragment="anchor">复制代码

生命周期

  • ngOnChanges  当组建绑定数据发生改变将会触发此生命周期
//OnChanges
ngOnChanges(changes: SimpleChanges): void {
    let value = changes.test && changes.test.currentValue
}复制代码
  • ngOnInit  在调用完构造函数、初始化完所有输入属性
//OnInit
ngOnInit(): void{
    
}复制代码
  • ngDoCheck  每当对组件或指令的输入属性进行变更检测时就会调用。可以用它来扩展变更检测逻辑,执行自定义的检测逻辑。
//DoCheck
ngDoCheck(): void {
    console.info('ok')
}复制代码
  • ngOnDestroy  只在实例被销毁前调用一次。
//OnDestroy
ngOnDestroy(): void {
    console.info('ok')
}复制代码

服务

为了不再把相同的代码复制一遍又一遍,我们要创建一个单一的可复用的数据服务,并且把它注入到需要它的那些组件中。 使用单独的服务可以保持组件精简,使其集中精力为视图提供支持,并且,借助模拟(Mock)服务,可以更容易的对组件进行单元测试。(引用官网)
@Injectable()
export class TestService {
    constructor() {
    }

    private data = {num:1};

    get num(){
        return this.data.num
    }

    add(){
        ++this.data.num
    }

    minus(){
        --this.data.num
    }
}复制代码

如何使用服务

  • 如果怎个项目已单例的模式,直接注入到 app.module.ts 元数据  providers 中即可
@NgModule({
    providers:[
        TestService
    ]
})复制代码
  • 非单例模式直接引入到自身的组件或模块的 providers中 即可。
@Component({
    providers:[
        TestService
    ]
})复制代码

依赖注入

依赖注入是重要的程序设计模式。 Angular 有自己的依赖注入框架,离开了它,几乎没法构建 Angular 应用。 它使用得非常广泛,以至于几乎每个人都会把它简称为 DI。(引用官网)

通过构造函数注入 TestService 实例,并把它存到名为 _testService 的私有属性中
export class IndexComponent{
    constructor(private _testService:TestService) {
    }
}复制代码
替代providers
@Injectable()
export class Test2Service extend TestService{
    constructor() {
        super();
    }
}

@Component({
    providers:[
        { provide: TestService, useClass: Test2Service}
    ],//依赖服务
})
export class IndexComponent{
    constructor(private _testService:TestService) {
    }
}复制代码

HTTP 服务

版本的跟新由之前的 HttpModule  模块 变更为  HttpClientModule  。
建议在app.module.ts 引入  HttpClientModule 
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        CommonModule,
        FormsModule,
        HttpClientModule,
    ],
    providers: [
        
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
} 复制代码
这样配置之后就可以任意模块或组件中使用 HttpClient  服务。
下面是几个比较常用的方法。
request(method: string, url: string, options: {
    body?: any;
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'any';
    withCredentials?: boolean;
}): Observable<any>;

get(url: string, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'any';
    withCredentials?: boolean;
}): Observable<any>;

post(url: string, body: any | null, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'any';
    withCredentials?: boolean;
}): Observable<any>;复制代码
这样用写,处理一些同样的操作时就不太方便,也不好维护,这边我的做法是用类统一封装一下,所有的接口调用都通过这个类处理。

//定义接口返回的参数字段 一般接口返回的参数都是固定的
export interface Result<T> {
    result?: any
    success?: any
    message?: any
}复制代码

export class ConfigService {
    static baseUrl    = 'http://127.0.0.1:8080';
    static uploadPath = 'http://127.0.0.1:8080';
    constructor(private _http: HttpClient) {

    }

    configForm() {
        return new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    }

    /**
     * @deprecated 直接通过FormData处理
     */
    configFormData() {
        return new HttpHeaders().set('Content-Type', 'multipart/form-data');//;charset=UTF-8
    }

    configJson() {
        return new HttpHeaders().set('Content-Type', 'application/json;charset=UTF-8');
    }

    postForm<T>(url, body = {}, config = {}): Observable<Result<T>> {
        return this._http.post<T>(ConfigService.baseUrl + url, qs.stringify(body), {headers: this.configForm(), ...config})
    }

    postFormData<T>(url, body = {}, config = {}): Observable<Result<T>> {
        const f = new FormData();
        for (let i in body) {
            f.append(i, body[i]);
        }
        return this._http.post<T>(ConfigService.baseUrl + url, f, {...config})
    }

    postFormDataUpload<T>(url, body = {}, config = {}): Observable<Result<T>> {
        const f = new FormData();
        for (let i in body) {
            if(body.hasOwnProperty(i)) f.append(i, body[i]);
        }
        return this._http.post<T>(ConfigService.uploadPath + url, f, {...config})
    }

    postJson<T>(url, body = {}, config = {}): Observable<Result<T>> {
        return this._http.post<T>(ConfigService.baseUrl + url, body, {headers: this.configJson(), ...config})
    }

    get<T>(url, body: any = {}, config = {}): Observable<Result<T>> {
        return this._http.get<T>(`${ConfigService.baseUrl + url}?${qs.stringify(body)}`, config)
    }
}复制代码
通过这样封装之后,不管什么方法,最终的参数传递都是  url, body, config 。方便管理。如果项目庞大,可以多加几个服务,按照模块划分,不同的模块由不同的 service 服务。

@Injectable()
export class UserService extends ConfigService {
    constructor(_http: HttpClient) {
        super(_http);
    }

    /**
     * 退出
     * @returns {Observable<Result<any>>}
     */
    quit() {
        return this.get(`url`)
    }

    /**
     * 登录
     * @returns {Observable<Result<any>>}
     */
    login(body = {},config = {}) {
        return this.postJson(`url`, body, config)
    }

     /**
     * 注册
     * @returns {Observable<Result<any>>}
     */
    register(body = {},config = {}){
        return this.postForm('url', body, config);
    }
}


复制代码
这样写的好处是结构清晰,协同开发比较友好,各自负责自己的模块。

HTTP拦截器

所有的接口请求都会通过拦截器,由它决定是否继续请求。类似 window.addEventListener('fetch',(event)=> {}) 这个监听事件。官网文档 移步
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
    constructor() {
    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({headers: req.headers});
        let xhr = next.handle(req);
        return xhr
            .do(response => {
                if (response instanceof HttpResponse) {
                    if (response.type == 4) {
                        if (response.status == 200) {
                            //...统一的逻辑处理,比如弹幕提示
                        } else if (response.status == 500) {
                            //...统一的错误处理
                        }
                    }
                }
            }).catch(error => {
                return Observable.throw(error || "Server Error");
            })
    }
}复制代码
使用方法如下,这样所有的接口请求都会经过 NoopInterceptor类。
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        CommonModule,
        FormsModule,
        HttpClientModule,
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: NoopInterceptor,
            multi: true,
        }
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
} 复制代码
如果想看angular的理论知识可以 移步

如何编写管道(Pipe)

Angular内置了一些管道,比如 DatePipeUpperCasePipeLowerCasePipeCurrencyPipePercentPipe。 它们全都可以直接用在任何模板中。(引用官网)
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
    /**
    * @value 预处理的值
    * @args  参数数组 {{value | keys:xxx:xxxx}} xxx、xxxx就是参数
    * @return 必须要有返回值
    */
    transform(value, args: string[]): any {
        let keys = [];
        for (let key in value) {
            keys.push({key: key, value: value[key]});
        }
        return keys;
    }
}复制代码
纯(pure)管道与非纯(impure)管道
//默认是纯Pipe
@Pipe({
    name: 'keys',
    pure: true,
})
//非纯Pipe
@Pipe({
    name: 'keys',
    pure: false,
})复制代码
他们的区别在于变更检测,如果数值未来将不会改变,则用纯管道,否者用非纯管道。

如何编写动画

在现在的版本当中,动画模块已经独立出去了,在向应用程序添加动画之前,需要将一些动画特定的模块和函数导入到根应用程序模块 BrowserAnimationsModule
@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule ],
})
export class AppModule { }复制代码

import {animate, style, transition, trigger} from '@angular/animations';

export const fadeIn = trigger('fadeIn', [
    transition('void => *', [
        style({opacity: 0}),
        animate(150, style({opacity: 1}))
    ]),
    transition('* => void', [
        animate(150, style({opacity: 0}))
    ])
]);

/**
* 使用方式
*/
@Component({
    animations:[fadeIn],
    template: `
       <div [@fadeIn]></div>
    `,
})
export class IndexComponent{
    constructor() {
    }
}复制代码
我这里只演示最简单的用法,建议去看官网文档,请 移步

路由异步加载

异步组件最小单位是模块 NgModule ,直接上代码。
  • user-list.component.ts
@Component({
    selector: 'app-user-list',
    templateUrl: './user-list.component.html',
    encapsulation: ViewEncapsulation.None,//html不做任何处理
    styleUrls: ['./user-list.component.less']
})
export class UserListComponent implements OnInit {
    
}复制代码
  • user-routing.module.ts
const routes = [
    {
        path: '',
        children:[
            {
                path: 'userList',
                component: UserListComponent
            },
        ]
    }
]
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class UserRoutingModule {
}复制代码
  • user.module.ts
@NgModule({
    declarations: [
        UserListComponent,
    ],
    imports: [
        UserRoutingModule
    ],
    providers: [],
})
export class UserModule {
}复制代码
  • app-routing.module.ts
const routes = [
    {
        path: '',
        component: IndexComponent,
        children:[
            {
                path: 'user',
                loadChildren: 'app/user/user.module#UserModule',
            },
        ]
    }
]
@NgModule({
    imports: [RouterModule.forRoot(routes, {useHash: true})],
    exports: [RouterModule]
})
export class AppRoutingModule {
}复制代码

如何编写一个业务组件

先分析这个组件需要一个什么样的结果,需要什么必要的参数,结构是怎么样子的,样子可以千变万化,可最终结果就只有一个。
如下图,做一个类似省市联动的组件,需求是获取被选中的省市ID集合,如果父级是勾中状态,则排除子集,如果父级是非全选状态也需要排除掉。
需求大概知道了以后,需要思考,这个组件将来可能用于其他的需求,在写组件的时候,尽量把功能细分。
  • directional-select.component.html
<p class="selected-text">
    当前已选择:
    <span>{{result().length}}</span>个
</p>
<div class="tags-box">
    <ul class="clearfix data-tags">
        <li *ngFor="let rl of resultList;let index = index">
            {{rl.name}}
            <i class="yc-icon icon" (click)="removeResultList(rl)">X</i>
        </li>
    </ul>
</div>
<div class="select-list-inner">
    <div class="scope" *ngFor="let list of cacheList;let index1 = index" [ngStyle]="{'width.%':100.0 / cacheList.length}">
        <ul class="list-with-select">
            <li class="spaui" *ngFor="let l of list;let index2 = index" (click)="pushCache(index1,index2,list)">
                <app-checkbox [(ngModel)]="l.selected" (eventChange)="areaItemChange(l)" [label]="l.name" [checkState]="l.checkState" [not_allow_selected]="l[hasCheckbox]"></app-checkbox>
                <i *ngIf="l[child]?.length > 0" class="icon yc-icon">&#xe664;</i>
            </li>
        </ul>
    </div>
</div>复制代码
这个组件依赖 app-checkbox完全可以用原生checkbox代替。
  • directional-select.component.less
.select-list-inner {
    background: #fff;
    width: 100%;
    border: 1px solid #ddd;
    max-height: 272px;
    overflow: auto;
    display: flex;
    .scope {
        &:first-child {
            border-left: none;
        }
        flex: auto;
        width: 0;
        overflow: auto;
        max-height: 270px;
        transition: width .2s;
        border-left: 1px solid #dfe1e7;
        .list-with-select {
            margin: 10px 0;
            .spaui {
                &:hover {
                    background: #f8f9fa;
                }
                height: 40px;
                line-height: 40px;
                padding-left: 20px;
                width: 100%;
                cursor: pointer;
                font-size: 15px;
                position: relative;
                > i {
                    float: right;
                    padding-right: 20px;
                }
            }
        }
    }
}

.tags-box {
    position: relative;
    border-top: 1px solid transparent;
    border-bottom: 1px solid transparent;
    margin-bottom: 10px;
    overflow-y: auto;
    max-height: 202px;
    overflow-x: hidden;
    transition: height .2s ease-in-out;
    ul.data-tags {
        width: 100%;
        position: relative;
        margin-bottom: 10px;
        li {
            float: left;
            margin-right: 5px;
            border: 1px solid #dfe1e7;
            border-radius: 20px;
            background: #f0f3f6;
            height: 34px;
            line-height: 32px;
            padding-left: 24px;
            padding-right: 8px;
            margin-top: 10px;
            font-size: 14px;
            transition: padding .2s ease-in-out;
            .icon {
                opacity: 0;
                transition: opacity .2s;
            }
            &:hover {
                background: #e1e7f1;
                padding-left: 16px;
                padding-right: 16px;
                transition: padding .2s ease-in-out;
                .icon {
                    opacity: 1;
                    transition: opacity .2s;
                    cursor: pointer;
                }
            }
        }
    }
}

.selected-text {
    float: left;
    line-height: 55px;
    padding-right: 10px;
    > span {
        font-size: 16px;
        font-weight: 700;
        color: #ff5e5e;
    }
}

复制代码
  • directional-select.component.ts
import {Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => DirectionalSelectComponent),
    multi: true
};

@Component({
    selector: 'directional-area-select',
    exportAs: 'directionalAreaSelect',
    templateUrl: './directional-select.component.html',
    styleUrls: ['./directional-select.component.less'],
    providers: [
        CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR
    ]
})
export class DirectionalSelectComponent implements OnInit, ControlValueAccessor {

    constructor() {
    }
    
    onChange = (value: any) => {
    };

    writeValue(obj: any): void {
        if (obj instanceof Array && obj.length > 0) {
            this.filterFill(obj);
            this.resultList = this.result(3);
        }
    }

    registerOnChange(fn: any): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: any): void {
    }

    ngOnInit() {

    }

    resultList;
    cacheList: any[] = [];
    private list: any[] = [];

    inputListChange() {
        if (this._inputList instanceof Array && this._inputList.length > 0) {
            this.list = this._inputList.map(d => {
                this.recursionChild(d);
                return d;
            });
            this.cacheList.length = 0;
            this.cacheList.push(this.list);
        }
    }

    _inputList;
    @Input('firstNotSelect') firstNotSelect = false;

    @Input('inputList') set inputList(value) {
        this._inputList = value;
        this.inputListChange();
    }

    @Input('value') value;
    @Input('hasCheckbox') hasCheckbox = 'not_allow_selected';

    @Input('child') child = 'options';
    @Output('eventChange') eventChange = new EventEmitter<any>();

    /**
     * 显示对应的子集数据列表
     * @param index1 当前层数下标
     * @param index2 当前层数列表的下标
     * @param list 当前层的列表数据
     */
    pushCache(index1, index2, list) {
        //往后选择
        let cl = this.cacheList[index1 + 1];
        let child = list[index2][this.child];
        if (child instanceof Array && child.length > 0) {
            if (!cl) {
                this.cacheList.push(child);
            } else {
                if (cl !== child) {
                    this.cacheList.splice(index1 + 1, 1, child)
                }
            }
        } else {
            if (cl !== child && !(child instanceof Array)) {
                this.cacheList.pop();
            }
        }

        //往前选择
        if (child && child.length > 0) {
            while (this.cacheList.length > index1 + 2) {
                this.cacheList.pop();
            }
        }
    }

    removeResultList(data) {
        data.selected = false;
        this.areaItemChange(data);
    }

    //选中有几个状态 对于父节点有 1全部选中 2部分选中 3全部取消 checkState 1 2 3
    areaItemChange(data) {
        if (data[this.hasCheckbox]) return;

        let child = data[this.child];

        if (data.selected) {
            data.checkState = 1
        } else {
            data.checkState = 3
        }

        //向下寻找
        if (child && child.length > 0) {
            this.recursionChildCheck(child)
        }
        //向上寻找
        this.recursionParentCheck(data);

        this.resultList = this.result(3);
        if (this.resultList instanceof Array && this.resultList.length > 0) {
            this.onChange(this.resultList.map(r => r.id));
        } else {
            this.onChange(null);
        }

        this.eventChange.next();
    }

    /**
     * 判断当前对象的父级中的子集被选中的个数和checkState == 2的个数来确定父级的当前状态
     * 递归
     * @param data
     */
    private recursionParentCheck(data) {
        let parent = data.parent;
        if (parent) {
            let l = parent[this.child];
            let length = l.reduce((previousValue, currentValue) => {
                return previousValue + ((currentValue.selected) ? 1 : 0)
            }, 0);
            let length2 = l.reduce((previousValue, currentValue) => {
                return previousValue + ((currentValue.checkState == 2) ? 1 : 0)
            }, 0);
            if (length == l.length) {
                parent.checkState = 1;
                parent.selected = true;
            } else if (length == 0 && length2 == 0) {
                parent.checkState = 3
            } else {
                parent.checkState = 2;
                parent.selected = false;
            }
            this.recursionParentCheck(parent);
        }
    }

    /**
     * 同步子集和父级的状态
     * 递归
     * @param list
     */
    private recursionChildCheck(list) {
        if (list && list.length > 0) {
            list.forEach(data => {
                let checked = data.parent.selected;
                data.selected = checked;
                if (checked) {
                    data.checkState = 1;
                    data.selected = true;
                } else {
                    data.checkState = 3;
                    data.selected = false;
                }
                let l = data[this.child];
                this.recursionChildCheck(l)
            })
        }
    }

    /**
     * 子集包含父级对象
     * 递归
     */
    private recursionChild(target) {
        let list = target[this.child];
        if (list && list.length > 0) {
            list.forEach(data => {
                data.parent = target;
                this.recursionChild(data)
            })
        }
    }

    /**
     * type 1 获取id集合 2获取key value 3获取对象引用
     * @param {number} type
     * @param {any[]} result
     * @returns {any[] | undefined}
     */
    result(type = 1, result = []) {
        if (this.firstNotSelect) {
            return this.recursionResult2(this.list, result, type);
        }
        return this.recursionResult(this.list, result, type);
    }

    /**
     * 只获取最后一层的值
     * @param list
     * @param {any[]} result
     * @param {number} type
     * @returns {any[] | undefined}
     */
    private recursionResult2(list, result = [], type = 1) {
        if (list && list.length > 0) {
            list.forEach(data => {
                let child = data[this.child];
                if (child && child.length > 0) {
                    this.recursionResult2(child, result, type);
                } else if (data.checkState == 1) {
                    switch (type) {
                        case 1:
                            result.push(data.id);
                            break;
                        case 2:
                            result.push({
                                id: data.id,
                                name: data.name,
                            });
                            break;
                        case 3:
                            result.push(data);
                            break;
                    }
                }
            })
        }
        return result;
    }

    private recursionResult(list, result = [], type = 1) {
        if (list && list.length > 0) {
            list.forEach(data => {
                //全部选中并且父级没有复选框
                if ((data[this.hasCheckbox] && data.checkState == 1) || data.checkState == 2) {
                    let child = data[this.child];
                    if (child && child.length > 0) {
                        this.recursionResult(child, result, type);
                    }
                    //全部选中并且父级有复选框 结果不需要包含子集
                } else if (data.checkState == 1 && !data[this.hasCheckbox]) {
                    switch (type) {
                        case 1:
                            result.push(data.id);
                            break;
                        case 2:
                            result.push({
                                id: data.id,
                                name: data.name,
                            });
                            break;
                        case 3:
                            result.push(data);
                            break;
                    }
                }
            })
        }
        return result;
    }

    filterFill(result) {
        //运用数据特性 判断时候选择了国外的选项
        this.cacheList.length = 1;
        let bo = result.find(n => {
            if (n == 1156 || String(n).length >= 6) return n
        });
        if (result instanceof Array && result.length > 0 && bo) {
            let child = this.list[0][this.child];
            while (child instanceof Array && child.length > 0) {
                this.cacheList.push(child);
                child = child[0][this.child];
            }
        } else {
            let child = this.list[1][this.child];
            while (child instanceof Array && child.length > 0) {
                this.cacheList.push(child);
                child = child[0][this.child];
            }
        }
        this.recursionFilter(result, this.list)
    }

    //递归过滤满足条件对象
    private recursionFilter(target, list, result = []) {
        if (target instanceof Array && target.length > 0) {
            list.forEach((data) => {
                let child = data[this.child];
                let bo = target.find((d => {
                    if (d == data.id) {
                        return d;
                    }
                }));
                if (bo) {
                    data.selected = true;
                    data.checkState = 1;
                    this.recursionChildCheck(child);
                    this.recursionParentCheck(data);
                }
                if (child instanceof Array && child.length > 0) {
                    this.recursionFilter(target, child);
                }
            })
        }
    }
}

复制代码
初始化状态是只包含顶层父级的列表,点击后将出现对应的子集列表,往后一直类推。
由此可见,可以声明一个变量 cacheList来储存顶层父级数据作为第一层,可以查看 inputListChange方法。 recursionChild方法是将所有的子集包含自己的父级引用。
pushCache显示对应的子集数据列表
areaItemChange checkbox发生改变的时候就会触发这个方法。这个方法完成的任务有向上寻找父级改变其状态,向下寻找子集改变其状态,将结果以标签的形式罗列出来,对应的方法可以查看 recursionChildCheck recursionParentCheck result(3)
此类实现了 ControlValueAccessor类 ,可以使用双向绑定来获取值。

路由守卫权限管理

上文也讲到了路由守卫 auth.guard.ts  ,这个类继承了 CanActivate  、CanActivateChild  类。

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
    constructor() {

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        //1.可以将当前的访问路由请求后台访问当前用户是否有权限,或者可以将权限存入本地缓存再进行判断。
        return Observable.create(false)
        //2.
        return new Promise((resolve, reject) => {
            setTimeout(()=> {
                resolve(false)
            },2000)
        })
        //3.通过本地缓存判断。
        return false
    }

    //子路由守护 父路由启用了子路由保护,进入自路由将会触发这个回调函数。
    canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.canActivate(childRoute, state);
    }复制代码
  • 路由配置 app-routing.module.ts  

const routes = [
    {
        path: '',
        component: IndexComponent,
        canActivate: [AuthGuard],
        children:[
            {
                path: 'user',
                loadChildren: 'app/user/user.module#UserModule',
            },
        ]
    }
]
@NgModule({
    imports: [RouterModule.forRoot(routes, {useHash: true})],
    exports: [RouterModule]
})
export class AppRoutingModule {
}复制代码

  •  user-routing.module.ts  

const routes: Routes = [
    {
        path: '',
        canActivateChild: [AuthGuard],//守护子路由
        children: [
            {
                path: 'userlist',
                component: UserListComponent,
                resolve: {jurisdiction: CurrentResolverService},
                data: {current: limitRole.userlist}
            }
        ]
    }
];
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class UserRoutingModule {
}复制代码



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值