Angular 2和Cloudkit JS - 解决响应承诺

时间:2016-08-18 08:50:18

标签: angular es6-promise angular2-services cloudkit-web-services

我试图让Angular 2与Cloudkit JS合作,目前这是一个简单的Todo。

todo.request.js

var todorequest = {
    get: function(){
        var container = CloudKit.getDefaultContainer();
        var publicDB = container.publicCloudDatabase;

        var query = {
            recordType: 'todo'
        };

        return publicDB.performQuery(query).then(function (response) {
            if(response.hasErrors) {
                throw response.errors[0];
            } else {
                let vals = [];
                response.records.forEach(function(record){
                    vals.push({title: record.fields['title'].value, text: record.fields['text'].value, date: record.fields['date'].value})
                })
                console.log(vals)
                return vals;
            }
        })
    }
}

这会返回Array [ Object, Object ]这就是我想要的,到目前为止都很好。

todo.service.ts 包含以下内容:

import { Injectable } from '@angular/core';
import { Todo } from './todo';

declare var todorequest:any;

@Injectable()
export class TodoService {

    constructor() {}

    getTodos() {
        return new Promise<Todo[]>(resolve =>
            todorequest.get() as Todo[] 
            );
    }
}

我假设从 todorequest.get()获得的是一个承诺,例如Object { Symbol(record)_1.k31kpejw2af: Object }。我怎么转换它做Todo [],所以我将能够使用数据?说实话,我不确定我做错了什么。

1 个答案:

答案 0 :(得分:2)

想出来!我在服务中缺少解决

getTodos() {
        return new Promise<Todo[]>(resolve =>
            resolve(todorequest.get())
            );
    }