angular 2数组列表未定义

时间:2017-01-18 07:28:02

标签: arrays angular

这是(数据) enter image description here

这是(data [0])enter image description here

这是我的HTML

<div  class="page">
<paper-card heading="Login Form">
  <div class="card-content">
    <paper-input [(ngModel)]="user.username" label="Username"></paper-input>
    <paper-input [(ngModel)]="user.password" label="Password" type="password"></paper-input>
  </div>
  <div class="card-actions" align="end">
    <paper-button class="login" id="Login" raised disabled (click)="Login(user)">Login</paper-button>
  </div>
</paper-card>
</div>

<paper-dialog id="wrong" modal>
  <p>Your username or password wrong please check again.</p>
  <div class="buttons">
    <paper-button dialog-confirm autofocus>Ok..</paper-button>
  </div>
</paper-dialog>

这是我的完整代码,当我试图从http res获取数组时显示未定义

Login(user){
        this._httpprovider.httpReq('http://localhost:5000/user','POST',{username:user.username, password:user.password},null).subscribe((data)=>{ 
                if (data.length > 0 ){
                    this._userdetails.setDetails(data);
                    this._router.navigate(['MainMenu']);
                    console.log(data.name); <<<<<<< here is the part
                }else {
                    var wmodal :any = document.getElementById('wrong');
                    wmodal.open();
                }

            });
        }

但如果我正在做console.log(data); 它显示了结果

Array[1]
0
:
Object
Name
:
"Admin"
Password
:
"Admin"
SBU
:
"IT"
Updateon
:
"2016-12-21T17:50:21.393Z"
UserName
:
"Admin"
__proto__
:
Object
length
:
1
__proto__
:
Array[0]

这是我从http req

获得的数组
[{"UserName":"Admin","Password":"Admin","Name":"Admin","SBU":"IT","Updateon":"2016-12-21T17:50:21.393Z"}]

我想得到的是名称= admin

这就是我为什么要做console.log(data.name)

1 个答案:

答案 0 :(得分:2)

OP编辑帖子后更新了答案

如果data首先是数组,则需要选择正确的元素。

喜欢

Login(user){
        this._httpprovider.httpReq('http://localhost:5000/user','POST',{username:user.username, password:user.password},null).subscribe((data)=>{ 
                if (data.length > 0 ){
                    this._userdetails.setDetails(data);
                    this._router.navigate(['MainMenu']);
                    console.log(data[0].Name); //<<<<<<< Assuming your data is correct
                }else {
                    var wmodal :any = document.getElementById('wrong');
                    wmodal.open();
                }
        });
}

旧回答

您正尝试在此代码中使用this访问本地变量。

test(){
  var b = []
  b = this.a; //<-- add this
  console.log(b.Name); //<-- remove this
}

此外,a是您字段中的对象,然后将其分配给测试中的空数组。

工作示例:http://plnkr.co/edit/ekmcCaiszsPoM1gV6NRQ?p=preview