类型“{}”上不存在属性“pname”

时间:2018-01-22 10:45:52

标签: json angular ionic2

我正在使用离子应用程序我正在使用firebase连接。 我从firebase获得了json,但是在迭代它时给了我错误。 我的provider.ts如下

export class MyProvider {
   masterdata : Array<any>;

   data : Array<any>;
  constructor(public afd: AngularFireDatabase) {
   }

 getDataByPage() {
 return this.afd.list('/masterdata/0/page/').valueChanges();
 }
}

我想将它传递给差异页面我的home.ts是

export class Home {
   home:Array<any>;
   data:any;
  constructor(public navCtrl: NavController, public navParams: NavParams, public popoverCtrl: PopoverController, public modalCtrl: ModalController,public masterdata: MyProvider ) {



    this.masterdata.getDataByPage().subscribe(result => {

    for(let i in result )
    {
        console.log(result[i]);
        if(result[i].pname == "Home")
        {
            this.data = result[i];
        }
    }

    });

  }
}

我的json是

 this.masterdata= {
    page: [{
        "pname": "Home",
        "pagetitle": "Most Recent",
        "list": [{
            img: 'assets/img/01.png',
            isAnimated: false
        }, {
            img: 'assets/img/02.png',
            isAnimated: false
        }, {
            img: 'assets/img/02.png'
        }, {
            img: 'assets/img/03.png'
        }]
    },
    {
        "pname": "Profile",
        "img": "assets/img/user-img.png",
        "name": "Justin Timberlake",
        "email": "Justin Timberlake@yahoo.com"
    }, ]
}

它给我的错误如下

Property 'pname' does not exist on type '{}'.

2 个答案:

答案 0 :(得分:0)

这应该有效result [i]['pname']

接下来尝试

let data = JSON.parse(result);
for(let i in data )
{
   console.log(data [i]);
   if(data [i].pname === "Home")
   {
     this.data = data [i];
   }
 }

普通JSON看起来像:

page: [{
    pname: "Home",
    pagetitle: "Most Recent",

答案 1 :(得分:0)

以下条件您可以使用Rxjs map运算符进行更改。检查您在控制台中获得的响应并相应地更新逻辑。但请确保您已导入RxJS库。

this.masterdata.getDataByPage().subscribe(result => res.json()).map(result =>{

  console.log(res);
  if(res.pname == "Home")
  {
    this.data = res;
  }
});