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