【问题标题】:How to solve errors in trying to store data from an array of objects in to new one如何解决尝试将对象数组中的数据存储到新对象中的错误
【发布时间】:2017-09-28 08:24:00
【问题描述】:

在此代码中,我尝试从 Web 服务中获取 tripIDNoteID 并将它们存储在行程中,然后通过读取 trips[i].noteID 缓存来自其他 Web 服务的其他参数,但会发生错误:

public trips= [{ "Token" : "" ,
          "UDI" : "",
          "tripID" : "",
          "NoteID":"",
          "START_ADDRESS":"",
          "END_ADDRESS":"",
          "NAME":"",
          "PHONE":"",
          "COST":"",
         }];

GetTrips(){
  let i = 0;
  let Url='http://mysitesite/gettrip/'+this.UDI+'/'+this.Token;
  console.log(Url);
  this.http.get(Url)
  .map(res => res.json())
            .subscribe(data => {            
          console.log(data);
          for(let note of data.notes) {
            this.trips[i].Token=this.Token;
            this.trips[i].UDI=this.UDI;
            this.trips[i].NoteID=note.ID;
            this.trips[i].tripID=note.TRIP;
            i++;
          }
          console.log(this.trips);
          }
    });
}

错误:

异常:无法设置未定义的属性“令牌”

异常:无法设置未定义的属性“UDI”

异常:无法设置未定义的属性“NoteID”

异常:无法设置未定义的属性“tripID”

更新 1: 这是@toskv 发布后的最新变化:

for(let note of data.notes) {
        let newTrip = {
            Token: this.Token,
            UDI: this.UDI,
            NoteID: note.ID,
            tripID: note.TRIP,
            START_ADDRESS :null,
            END_ADDRESS:null,
            NAME:null,
            PHONE:null,
            COST:null,
       };
          this.trips.push(newTrip);
          }
          console.log(this.trips);
          this.trips =this.trips.slice(1);
          console.log(this.trips.length);

          } 

【问题讨论】:

  • 您应该真正了解一下数组在 js 中的工作原理。现在你在 for. 里面做 undefined.Token

标签: arrays typescript ionic2


【解决方案1】:

获取数组中不存在的索引的值将导致返回undefined值。

相反,您应该在数组中推送新值。

GetTrips() {

  let Url = 'http://mysitesite/gettrip/' + this.UDI + '/' + this.Token;
  console.log(Url);
  this.http.get(Url)
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);

        for (let note of data.notes) {
          let newTrip = {
            Token: this.Token,
            UDI: this.UDI,
            NoteID: note.ID,
            tripID: note.TRIP
          };
          this.trips.push(newTrip);

        }
        console.log(this.trips);
      }
    });
}

【讨论】:

  • 嗨@toskv,首先非常感谢你,接下来经过测试,我强制添加:` COST:null,END_ADDRESS:null, NAME:null,PHONE:START_ADDRESS:null ` 到 newTrip。然后它为 0 索引添加一个空对象。
  • 我无法想象这会是什么样子,您能用您更改的代码更新您的问题吗?
  • 切片是怎么回事?同样在原始帖子中,当您定义trips 数组时,您使用其中的现有项目执行此操作。我猜这就是你要到达的那个。您是否尝试定义该数组中项目的类型?
  • 嗨@toskv 你能检查一下吗:我已经解释了这个页面中的其他问题forum.ionicframework.com/t/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
相关资源
最近更新 更多