I've been using let _this = this
or _component
for a while to reference the scope of angular components when functions become complex and include a couple of levels of nesting.
This was recommended to me in a question months ago to get around the issue of accessing the correct scope within such functions, but is there any way that I can get around this and consistently reference the scope of the component itself just using this
as the identifier?
I've had a look for anything that ES6 might be able to fix this with, but can't figure out a way to solve this issue.
Example - _this overload:
addPayment() {
let _this = this;
console.log('ViewInvoice.addPayment()');
this.newPaymentDialogRef = this.dialog.open(NewPaymentDialogComponent, {
hasBackdrop: true,
data: {
userId: _this.authService.user.uid,
invoice: _this.invoice,
payments: _this.payments
}
})
this.newPaymentDialogRef.afterClosed().subscribe(payment => {
if (payment) {
_this.payments.push(payment);
_this.paymentsData.data = _this.payments;
_this.db.collection('/users').doc(_this.authService.user.uid).collection('/invoices').doc(_this.invoice.id).collection('/payments').doc(payment.id).set(payment)
.then(function(docRef) {
console.log('ViewInvoice.addPayment() - New payment saved:', payment);
_this.notifService.showNotification('Payment added', 'Close');
})
.catch(function(error) {
console.error(`ViewInvoice.addPayment() - Error saving new payment: ${error.message}`);
_this.notifService.showNotification(`Error adding new payment: ${error.message}`, 'Close');
})
_this.calcPaymentTotals(payment);
}
})
}