无法获得组件的数据角度服务

时间:2018-02-21 13:16:02

标签: angular nativescript angular-services

我的服务功能是..

 getPro():any{
    this.database.all("SELECT * FROM product").then(rows => {
        console.log("hello pro hear....")
        let proList:Product[]=[]

        for(var row in rows) {

            proList.push(new Product(rows[row][0],rows[row][1],rows[row][2],rows[row][3],rows[row][4]))
           /* proList.push({
                "id": rows[row][0],
                "name": rows[row][1],
                "hsn": rows[row][2],
                "rate": rows[row][3],
                "tax":rows[row][4]
            })*/
            console.log("list ",rows[row][0])
        }
        console.log("total pro ",proList.length)
        return "hello"
    }, error => {
        console.log("SELECT ERROR", error);
    });
}

我的组件是......

 proList:any

fatchPro(){
   this.proList= this.dataservice.getPro();
    console.log("fatchPro" ,this.proList)
}

但是当我在console.log(proList)时它会得到未定义的

我该如何解决这个错误...

2 个答案:

答案 0 :(得分:1)

试试

 getPro():any{
    return this.database.all("SELECT * FROM product").then(rows => {
        console.log("hello pro hear....")
        let proList:Product[]=[]

        for(var row in rows) {

            proList.push(new Product(rows[row][0],rows[row][1],rows[row][2],rows[row][3],rows[row][4]))
           /* proList.push({
                "id": rows[row][0],
                "name": rows[row][1],
                "hsn": rows[row][2],
                "rate": rows[row][3],
                "tax":rows[row][4]
            })*/
            console.log("list ",rows[row][0])
        }
        console.log("total pro ",proList.length)
        return "hello"
    }, error => {
        console.log("SELECT ERROR", error);
    });
}

fatchPro(){
   this.proList= this.dataservice.getPro().then(list =>
   {
   this.proList = list;
    console.log("fatchPro" ,this.proList)
   });

}

答案 1 :(得分:0)

你的dataservice.getPro function正在创建一个Promise并订阅它,但不会返回任何内容。因此,proList未设置。您可以在fatchPro function

中退回承诺并订阅该承诺
getPro(): Promise<any>{
    return this.database.all("SELECT * FROM product").then(rows => {
        return rows.map(row => new Product(row[0], row[1], row[2], row[3], row[4]));
    }, error => {
         console.log("SELECT ERROR", error);
    });
}

-

proList: Product[];

fatchPro() {
   this.dataservice.getPro().then(proList => {
       this.proList = proList;
       console.log("fatchPro" ,this.proList);
    });
}