我正在使用Lambda函数从数据库中获取数据,并希望等到它在我的页面呈现之前到达。
我知道有一个promises和* ngIf的组合来完成这个(as it is explained here),但是我不知道如何在我的代码中实现它。
这是我的代码:
overview.component.ts
export class OverviewComponent implements OnInit {
businessPartner: any;
bpNumber: number;
paymentDetail: PaymentDetails;
response: any;
constructor() { }
ngOnInit() {
AWS.config.update({
//Testuser
accessKeyId: "XXXXXXXXXXXXX",
secretAccessKey: "XXXXXXXXXXXXXXXXXX",
region: "eu-west-1",
});
//get bpNumber from session storage
this.bpNumber = +JSON.parse(sessionStorage.getItem('bpNumber'));
this.lambdaGetBp(this.bpNumber);
};
lambdaGetBp(bpNumber: number): any{
var lambda = new AWS.Lambda();
var params = {
FunctionName: 'readFromDynamoDb', /* required */
Payload: JSON.stringify({
bpNumber : bpNumber,
})
};
lambda.invoke(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
var jsonObj = JSON.parse(data.Payload)
console.log(jsonObj) // successful response
return jsonObj;
}
});
}
click(){
console.log(this.businessPartner);
}
}
我的Lambda函数index.js
'use strict';
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' });
exports.handler = function(e, ctx, callback) {
let table = "dsbTable";
let bpNumber = e.bpNumber;
let params = {
TableName: table,
Key: {
"bpNumber": bpNumber
},
};
docClient.get(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
callback(err, null);
} else {
var xml2js = require('xml2js'); // XML2JS Module
var parser = new xml2js.Parser(); // Creating XML to JSON parser object
parser.parseString(data.Item.getBp, function(err, result) { // creating javascript objects from every XML-entry <=== THIS IS NOT PRETTY :(
if (err) {
console.log('Error!!!!!!')
} else {
data = result;
console.log('Done');
}
});
};
callback(null, data);
});
};
感谢您的帮助:)
答案 0 :(得分:2)
好吧,我终于明白了,实际上非常容易。
我只需要在lambdaGetBp()
- 方法周围放置一个Promise,或者更确切地说围绕它内部的代码。
现在看起来像这样:
lambdaGetBp(bpNumber: number){
return new Promise((resolve, reject) => { //HERE
var lambda = new AWS.Lambda();
var params = {
FunctionName: 'readFromDynamoDb', /* required */
Payload: JSON.stringify({
bpNumber : bpNumber
})
};
lambda.invoke(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
var jsonObj = JSON.parse(data.Payload);
console.log(jsonObj); // successful response
resolve(jsonObj); // AND HERE
}
});
});
}
然后将其称为ngOnInit()
this.lambdaGetBp(this.bpNumber).then(data => this.bp= data);