【问题标题】:Angular 2 how to return array of objects from nested promiseAngular 2如何从嵌套的promise中返回对象数组
【发布时间】:2017-04-03 09:27:27
【问题描述】:

我正在尝试编写一个服务来获取客户列表,但我不知道从嵌套促销中返回客户列表。

请提前帮我解决这个问题。

import { Injectable } from '@angular/core';
import { SQLite } from 'ionic-native';

@Injectable()
export class CustomerService {
    private sDBName:string;
    private db;
    private isDBExist:boolean = false;

    constructor() {}

    setDBName(sDBName:string) {
        this.sDBName = sDBName;
    }

    connect():Promise<any> {        
        this.db = new SQLite();
        return this.db.openDatabase({
            name: this.sDBName,
            location: 'default'
        });
    }
    getCustomersList():Promise<any> {
        return Promise.resolve(()=>{            
            return this.connect().then(()=>{                
                this.isDBExist = true;
                let sql = 'SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10';
                return this.db.executeSql(sql, {}).then((result)=>{ 
                    let customers = [];             
                    for(let i=0; i<result.rows.length; i++) {
                        customers.push(result.rows.item(i));
                    }
                    return customers;
                },(err)=>{
                    this.debug('Unable to select customers', err);
                    return [];
                });
            },(err)=>{
                this.debug('Unable to open database', err);
                return [];
            });
        });
    }
}

【问题讨论】:

  • 有什么问题?您在哪里以及如何拨打getCustomerList()
  • 我不知道如何返回客户列表getCustomersList() 这个代码在getCustomersList() 中有一些问题我想不通
  • return Promise.resolve(()=&gt;{ ... }) 用一个函数解析,它不调用它。有什么理由不应该是return this.connect()...
  • return 语句不等待解决承诺。它的返回是空的。如何让return语句等待

标签: javascript cordova angular typescript ionic2


【解决方案1】:

你需要用.then(...)like链接调用

this.getCustomerList().then(result => this.myArray = result);

【讨论】:

  • 你能澄清我只有一件事是getCustomerList()函数是对的
  • angular 2 return statement will wait for the promise to be completed
  • 这个问题只和这个stackoverflow.com/questions/37841721/…有关。
猜你喜欢
  • 2019-01-09
  • 1970-01-01
  • 2017-03-24
  • 2013-10-26
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多