Spread Operator

序言
本周在写分页查询的时候遇到了关于...运算符的问题,想到之前例会提过这个运算符,但是当自己独立使用时还是会遇到问题。

分页查询

查询条件:name

export class TeacherIndexComponent implements OnInit {

    pageable = new Pageable();
    loading = true;
    isOkLoading = false;
    teachers = new Array();
    teacherPage = new Page();
    params: Params;
    nameFormControl = new FormControl('');

    constructor(private teacherService: TeacherService,
                private systemConfig: SystemConfigService,
                private route: ActivatedRoute) {
    }

    // 初始化
    ngOnInit() {
        this.route.queryParams.subscribe((params: {page?: string, size?: string}) => {
            this.nameFormControl.setValue(params['name']);
            this.reload(params);
        });
    }

    onSubmit(): void {
        const name = this.nameFormControl.value;
        this.reload({...this.params, ...{name}});
    }

    /**
     * 查询
     * @param params page: 当前页 size: 每页大小
     */
    reload(params: Params): void {
        // 发起查询params
        this.params = params;
        this.teacherService.pageByName(
            // 调用stringToIntegerNumber将查询的字符串转为number
            getDefaultWhenValueIsInValid(params['page'], '0'),
            getDefaultWhenValueIsInValid(params['size'], this.systemConfig.getPageSize()),
            {
                name: params['name'],
            },
        ).subscribe(page => {
            this.teacherPage = page;
        });
    }

    /**
     * 点击分页
     * @param page 当前页
     */
    onPageChange(page: number): void {
        this.reload({...this.params, ...{page}});
    }

    /**
     * 点击改变每页大小
     * @param size 每页大小
     */
    onSizeChange(size: number): void {
        this.reload({...this.params, ...{size}});
    }
}

这是正确代码,但是当我将 onSubmit()方法改成如下:

onSubmit(): void {
        // 将{name}直接改成this.nameFormControl.value
        this.reload({...this.params, ...this.nameFormControl.value});
    }

此时如果nameFormControl.value为'name',那么在控制台打印的结果就是:
Spread Operator_第1张图片
将一个‘name’字符串直接变成一个数组对象?

踩坑记录

此时当我使用param['name]时,获取到的恒为undefined,不断打断点之后发现错误所在。
对比其他写法:{...this.params, ...{xxx}}

猜测:

const name1 = 'name';
console.log({name1}); // 打印结果是{name1: 'name'}

结果:

Spread Operator_第2张图片

Spread Operator

何为扩展操作符呢?

The main objective of the spread operator is to spread the elements of an array or object.
简言之:扩展数组或对象元素

扩展对象使用
示例一:

const point2D = {x: 1, y: 2};
const anotherPoint3D = {x: 5, z: 4, ...point2D};
console.log(anotherPoint3D); // {x: 1, y: 2, z: 4}
const yetAnotherPoint3D = {...point2D, x: 5, z: 4}
console.log(yetAnotherPoint3D); // {x: 5, y: 2, z: 4}

示例二:

const foo = {a: 1, b: 2, c: 0};
const bar = {c: 1, d: 2};
/** Merge foo and bar */
const fooBar = {...foo, ...bar};
// fooBar is now {a: 1, b: 2, c: 1, d: 2}

你可能感兴趣的:(angular)