我正在使用Promise发出POST请求。我无法使用POST请求中返回的JSON数组更新全局变量records
。
Export class WalletPage {
private emailAddress;
apiUrl = 'someapiurl';
// records = [
// // { fieldA:'1', fieldb:one},
// // { fieldA:'2', fieldb:two}
// ];
records = [];
constructor(public navCtrl: NavController, private httpClient: HttpClient) {
this.restProvider = new RestProvider(this.httpClient);
}
submitEmail() {
console.log('Trying to submit user email address: ', this.emailAddress);
var rp = require('request-promise');
const payload = {"email_address": this.emailAddress}
const records = [];
var options = {
method: 'POST',
uri: this.apiUrl + '/order/userRecords',
body: payload,
json: true
};
rp(options)
.then(function (parsedBody) {
// POST succeeded...
const someResponse = parsedBody.entries
for (var i = 0, len = someResponse.length; i < len; i++) {
console.log(someResponse[0]);
records.push(someResponse[0])
console.log('someArray is', records)
this.records = records;
}
})
.catch(function (err) {
// POST failed
});
}
}
看来this.records = records;
实际上没有更新全局变量。我这样做是因为离子框架会识别这样的数组,并且可以在每个条目的表格中填充一行。
离子前端代码:
<ion-list-header>
Your records
</ion-list-header>
<ion-item *ngFor="let record of records">
<ion-label>{{record.fielda}} with value: {{record.fieldb}} </ion-label>
</ion-item>
答案 0 :(得分:0)
这个变量不是WalletPage,它是窗口或其他东西,你应该像这样改进你的代码:
rp(options)
.then((parsedBody) => {
});
或:
rp(options)
.then(function (parsedBody) {
}.bind(this));