0
问题是,我希望确保数据在我继续执行我的程序之前可用,所以我需要使用异步类型函数。根据ion.io,Promise似乎是标准方法。无法承诺在Ionic2打字稿中使用Trello
我有一个非常简单的例子,下面基本上来自Trello.com网站制作一张卡片。然后,我将这个id加载到一个全局数组中,然后尝试记录它。
// myTry.ts开始的
import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
//compile needs this and it seems to make the Trello functions work
declare var Trello: any;
@Component({
templateUrl: 'build/pages/mytry/mytry.html'
})
export class MyTryPage {
fileEntry: any;
myData: any;
myList: any = "MyList ID - get this from the sandbox screen in Trello.com please";
newCard = {
name: '****My New Test Card',
desc: '****This is the description of our new card.',
idList: this.myList,
pos: 'top'
};
readTrello: any = function() {
Trello.post('/cards/', this.newCard, this.creationSuccess);
}
constructor(private navController: NavController) {
Trello.authorize({
type: "redirect",
interactive: "true",
name: "My Application",
scope: {
read: "true",
write: "true" },
expiration: "never",
success: this.authenticationSuccess,
error: this.authenticationFailure
});
this.testPromise();
// this line does not work
console.log('My data ' + this.myData); // returns undefined
}
testPromise: any = function() {
var p1 = new Promise(resolve => {
this.readTrello();
window.setTimeout(() => {
// this line is run after timeout completes so why is data not available
console.log("Since this is run after timeout, I expect data to exist???? "+ this.myData);
resolve(0);
}, 5000);
});
p1.then(
// Log the fulfillment value
() => {
//This fails - data is NOT available
console.log('Promise fullfilled. Data should be available:???? Array is no longer in scope at all????' + this.myData);
// I will load into displayable structure here later
})
.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
}
authenticationSuccess: any = function() {
//This works
console.log("Successful authentication");
};
authenticationFailure: any = function() {
console.log("Failed authentication");
};
creationSuccess: any = function(data) {
//This works
console.log('Trello callback successfull');
this.myData = JSON.stringify(data.id);
//This works and the data returned is available and correct - great.
console.log('Card created successfully. Data returned:' + this.myData);
};
}
我失去了一些东西 - 数据是超时之前可用,但不是之后???很明显,我的程序流程不正确。 ps我可以使用令牌做到上面,但我想使用Trello发布的API。
谢谢Paarth,我更换了,因为我认为你曾建议让他们拉姆达功能,但得到了同样的结果,当我跑的代码。数据在回调中可用,但不能在以后。我假设我的数据不在范围内。 – Tonyeng
我还在构造函数中添加了一个console.log行,以查看myData是否可用 - 不是。也许我已经声明了myData,这也是一个问题。 – Tonyeng
在这一行:'Trello.post('/ cards /',this.newCard,this.creationSuccess); '而不是通过'this.creationSuccess'尝试通过'this.creationSuccess.bind(this)' – Paarth