Angular 2中TypeScript数组转字符串为空的问题排查
问题分析与解决方案
这问题我之前踩过一模一样的坑!核心原因是HTTP请求是异步操作,你调用create_hidden_qp()的时机不对——当你执行join()的时候,fieldlist还没被subscribe里的代码填充呢!
为什么会出现这种矛盾的现象?
this.http.get()是异步执行的,subscribe里的回调函数只有等HTTP请求成功返回后才会触发,这时候才会把res.fields的元素逐个推到fieldlist里。- 你调用
create_hidden_qp()的时候,大概率是在HTTP请求还没完成的阶段,这时候fieldlist还是初始化的空数组[],所以join()自然得到空字符串""。 - 至于直接打印
this.fieldlist能看到完整内容,是因为浏览器控制台会动态更新引用类型的显示——你看到的是请求完成后数组的最终状态,而不是调用console.log("hello", this.fieldlist)那一刻的数组状态。如果想验证这一点,你可以改成console.log("hello", [...this.fieldlist])(浅拷贝数组),这时候就能看到调用时数组确实是空的。
对应选项分析
你的三个选项里没有直接命中“异步时机”的选项,但我们可以逐个排除:
- A) 声明错误?:
fieldlist: string[] = [];的声明完全正确,初始化了一个空的字符串数组。 - B) 赋值错误?:赋值逻辑本身没问题,
res.fields.forEach(element => this.fieldlist.push(element));能正确把元素推到数组里,只是执行时机太晚,赶不上create_hidden_qp()的调用。 - C) 数组元素访问错误?:
join()是数组的标准方法,没有访问逻辑错误。
解决方案
你需要确保create_hidden_qp()在fieldlist被填充完成后再执行,这里给你几种常见的实现方式:
方式1:把函数调用放到subscribe回调里(最直接)
this.http.get(getform_endpoint,requestOptions) .map((res: Response) => res.json()) .subscribe( res => { this.FormData = res.schema; res.fields.forEach(element => { this.fieldlist.push(element); }); // 数组填充完成后再调用目标函数 this.create_hidden_qp(); });
方式2:用RxJS的tap操作符预处理数组(更符合RxJS风格)
this.http.get(getform_endpoint,requestOptions) .map((res: Response) => res.json()) .tap(res => { this.FormData = res.schema; this.fieldlist = [...res.fields]; // 直接赋值比循环push更高效 }) .subscribe(() => { this.create_hidden_qp(); });
方式3:让create_hidden_qp接受数组参数(解耦依赖)
// 修改目标函数,让它依赖传入的参数而非组件变量 create_hidden_qp(fields: string[]) { let elementsnamevalue = fields.join(); console.log("hello", elementsnamevalue); } // 在subscribe里传入填充好的数组调用函数 this.http.get(getform_endpoint,requestOptions) .map((res: Response) => res.json()) .subscribe( res => { this.FormData = res.schema; this.fieldlist = [...res.fields]; this.create_hidden_qp(this.fieldlist); });
这样就能保证你在处理数组的时候,它已经被正确填充完成了。
内容的提问来源于stack exchange,提问作者Code is Cheap Show me The Talk
相关产品推荐
相关产品推荐

