在居民抉择组件的编写中我起初的想法是实现如上图这样的成果——显示居民的姓名、电话号码、身份证号,并依据小区和楼栋进行分组,然而在分组这里呈现了一些bug。
我再获取居民时是通过先获取所有的居民再通过.filter
进行筛选来获取所需的居民。
residents = residents.filter(residents => this.isContained(districtIds, residents.houses.map(houses => houses.unit.building.village.community.id)))
isContained(numbers: Array<Number>, newNumbers: Array<Number>): boolean { return newNumbers.filter((x) => { return numbers.includes(x); }).length != 0; }
其中isContained
函数用来判断两个数组是否有交加,如果有则返回true,这样的话只有该居民在指定范畴内有屋宇就会被获取到。
然而在用groupBy
和groupValue
进行分组时就呈现了问题
groupBy(resident: Resident) { return resident.houses[0].unit.building.id; }; groupValue(key: string | object, children: Resident[]): Building { const building = children[0].houses[0].unit.building; Assert.isDefined(building.name, 'name must be defined'); Assert.isDefined(building.village.name, 'name must be defined'); return building; }
起初我想间接依照第一个屋宇进行分类,然而测试后发现如果该居民在其余区域也有屋宇,并且是第一位那么就会按这个屋宇进行分类,尽管居民属于该治理区域然而分类的类别不属于该治理区域,这很显著就不合乎咱们的需要。
于是我进行了如下改变:
起初我想的是只须要在groupBy
和groupValue
中退出断定,在收到的resident中寻找在管辖范畴内的屋宇,在进行返回。
groupBy(resident: Resident) { const ids = resident.houses.map(houses => houses.unit.building.village.community.id); const index = ids.indexOf(this.districtIds[0]); return resident.houses[index].unit.building.id; };groupValue(key: string | object, children: Resident[]): Building { const buildings = children[0].houses.map(houses => houses.unit.building); const communityIds = buildings.map(buildings => buildings.village.community.id); const index = communityIds.indexOf(this.districtIds[0]); const building = buildings[index]; Assert.isDefined(building.name, 'name must be defined'); Assert.isDefined(building.village.name, 'name must be defined'); return building;}
其中的this.districtIds
是在ngOnInit中调用相应M层办法失去的。
this.districtService.getDistrictsOfCurrentLoginUser(DISTRICT_TYPE.community.value).subscribe(districts => { const districtIds = districts.map(value => value.id); this.districtIds = districtIds; console.log("ngOnInit"); console.log(this.districtIds); ...}
然而在运行时会产生报错——TypeError: Cannot read properties of undefined (reading 'districtIds')
,即this为空,之后尝试在groupBy
中进行这样的输入——console.log(this);
,后果果然为undefined;
在谷歌上查问后发现有人的状况和我有一点类似——都是呈现了this为undefined,然而他的问题是在一个回调函数中应用this,当它被执行时,范畴是不同的。
比方咱们在编译器中输出如下代码:
var Bob = { sname: "鲍勃", friends: ["Jack", "Rose", "Tom", "Jerry"], intr() { this.friends.forEach(function (ele) { console.log(this.sname + "意识" + ele);@此行产生报错 }); } }
编译器会在@所处行产生报错,并会给出解决办法——改为箭头函数即
intr() { this.friends.forEach((ele) => { console.log(this.sname + "意识" + ele); }); }
所以集体猜想此处的groupBy
函数也被当作了回调函数,然而此处将办法改为箭头函数显然不实用,通过查问又发现了另一种办法——用bind办法将this与该办法进行绑定。它会创立一个与原来函数主体雷同的新函数,新函数中的this指向传入的对象。
咱们能够在构造函数中调用此办法如下所示
constructor(private residentService: ResidentService, private districtService: DistrictService) { this.groupBy = this.groupBy.bind(this); this.groupValue = this.groupValue.bind(this); }
之后咱们再在此处应用this指针就能够像咱们所想的那样区执行。