乐趣区

关于angular:Spread-Operator

序言
本周在写分页查问的时候遇到了对于 ... 运算符的问题, 想到之前例会提过这个运算符,然而当本人独立应用时还是会遇到问题。

分页查问

查问条件:name

export class TeacherIndexComponent implements OnInit {pageable = new Pageable();
    loading = true;
    isOkLoading = false;
    teachers = new Array<Teacher>();
    teacherPage = new Page<Teacher>();
    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’,那么在控制台打印的后果就是:

将一个 ‘name’ 字符串间接变成一个数组对象?

踩坑记录

此时当我应用 param[‘name]时,获取到的恒为 undefined,一直打断点之后发现错误所在。
比照其余写法:{…this.params, …{xxx}}

猜想:

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

后果:

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}
退出移动版