Angular中Push操作符在API调用时无法保留已有值问题
问题原因分析
你的问题出在变量作用域和赋值逻辑上:
- 在
getCountryByContinentIdByUserId方法里,每次调用都会重新创建空的Contrynames数组,把当前大洲的国家名称存入后直接转成字符串赋值给this.contries1——这导致每次处理新大洲时,之前的国家数据被完全覆盖,而非累加。 - 虽然
ContinentNames在getContinentByUserId里是一次性收集所有大洲,但直接转成字符串存储会丢失可修改性,后续执行Push操作添加新数据时无法直接追加内容。
修复方案
1. 调整组件变量类型
先把组件内的ContinentNames和contries1改成数组类型(不要一开始就用字符串),在组件类里声明:
// 组件类内的变量声明 ContinentNames: string[] = []; contries1: string[] = [];
2. 修改getContinentByUserId方法
去掉方法内局部的ContinentNames数组,直接往组件的数组里追加数据,若需要字符串格式可单独处理:
getContinentByUserId(userId: string) { if (userId === undefined) { return; } // 重新获取权限时清空旧数据(按需保留) this.ContinentNames = []; this.contries1 = []; this.continentService.getcontinentByUserId(userId).subscribe((data: any) => { this.continents = data.sort((a, b) => a.name.localeCompare(b.name)); // 直接向组件的大洲数组追加内容 this.continents.forEach(con => this.ContinentNames.push(con.name)); // 若需要字符串格式,单独存储 // this.continentNamesStr = this.ContinentNames.join(','); for (const index of data) { this.getCountryByContinentIdByUserId(index.id, userId) } }); }
3. 修改getCountryByContinentIdByUserId方法
同样去掉局部的Contrynames数组,直接把当前大洲的国家追加到组件的contries1数组中:
getCountryByContinentIdByUserId(ContinentId: string, userId: string) { if (ContinentId === undefined || userId === undefined) { return; } this.contryService .getContriesByUserId(ContinentId, userId) .subscribe((data: any) => { this.counties = data.sort((a, b) => a.name.localeCompare(b.name)); // 向组件的国家数组追加当前大洲的国家 this.counties.forEach(min => this.contries1.push(min.name)); // 若需要字符串格式,单独处理 // this.contries1Str = this.contries1.join(','); for (const index of data) { this.getStatesByContryIdByUserId(index.id, userId); } }); }
4. 后续Push操作的处理
之后添加新的大洲/国家权限时,直接往对应的组件数组里push即可,示例:
// 添加新大洲 this.ContinentNames.push('新大洲名称'); // 添加新国家 this.contries1.push('新国家名称'); // 若需要同步字符串格式,更新对应变量 this.continentNamesStr = this.ContinentNames.join(','); this.contries1Str = this.contries1.join(',');
这样就能保证每次添加新数据时,旧数据不会被删除,而是持续累加。
内容的提问来源于stack exchange,提问作者Ravi Dharoju
相关产品推荐
相关产品推荐

