将字符串从json响应转换为数字-* ngFor-Angular 6

时间:2019-03-08 07:16:57

标签: json angular loops angular6

我正在尝试将一些字符串从json响应转换为数字。例如

邮政编码:“ 92998-3874”至92998-3874。碰到了这个SO。但不要失败。接下来,我需要在我的视图中循环播放它,但是在堆栈闪电战控制台中遇到以下错误。

ERROR
Error: Cannot find a differ supporting object '[object Object]' of type 'Clementina DuBuque'. NgFor only supports binding to Iterables such as Arrays.
Unable to display error. Open your browser's console to view.

到目前为止:

export class AppComponent {
  name = 'Angular';
  private _userList = [];
  private _userListAddress:any = [];
  _sampleURL = 'https://jsonplaceholder.typicode.com/users';

  constructor(private _http: HttpClient) { }
  _loadData() {
    this._http.get<any[]>(this._sampleURL).subscribe(data => {
      this._userList = data;
      this._userListAddress = data[0].address.suite;
      console.log(this._userList);

      for (var _address in this._userList) {
       this._userListAddress = this._userList[_address];
        console.log('address', 
        parseInt(this._userListAddress.address.zipcode));

        /* 

        //below snippet is used to convert strings to num

        [].forEach.call(this._userList, function (a, b) {          
          [].forEach.call(Object.keys(a), function (c) {            
            if (!isNaN(this._userList[b][c]))             
              this._userList[b][c] = +this._userList[b][c];
          });
        });
        console.log(this._userList); */
      }
    }
    )
  }
}


<button (click)="_loadData()">Load data</button>

<div *ngFor="let list of _userList">
<ul>
<li>{{list.address.zipcode}}</li>
</ul>

<div *ngFor="let addresList of _userListAddress">
    <ul>
<li>{{addresList.address.zipcode}}</li>
</ul>
</div>
</div>

哪里做错了,或者提出了更好的方法来实现这一目标。 帮助非常感谢。

Stack Blitz

1 个答案:

答案 0 :(得分:1)

如果我们正在谈论这个问题:

def test():
    while True:
        val = raw_input("enter IP:")
        try:
            IP=ipaddress.ip_network(str(val),True)
        except:
            if val == "":
                print " Enter subnet:"
            else:
                print " IP should be formatted X.X.X.X/Y"

test()

在这里:

ERROR
Error: Cannot find a differ supporting object '[object Object]' of type 'Clementina DuBuque'. NgFor only supports binding to Iterables such as Arrays.
Unable to display error. Open your browser's console to view.

for (var _address in this._userList) { -是

这样的用户对象
_address

,然后您尝试从用户数组中获取用户对象,而绕过了作为错误键的用户对象。     "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" }

所以这不是对话问题,只需检查代码流。

  

更新

只需替换特殊字符然后解析:

this._userListAddress = this._userList[_address];