Reputation: 9564
I'm basically counting the number of times an object in an array has 2 keys that equals a certain value. I want to increment that number for each time the condition is met.
if I console.log to see the number of times the 'for' loop is firing, everything is good and all works well. But when I try to do something with this.multidropAccepted I'm suddenly getting undefined errors, even when I'm just trying to read it on the console.
Code:
function countAccepted(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].DeliveryStatus == "Accepted" && arr[i].BookingId == "0") {
console.log("poop");
this.multidropAccepted++;
}
}
}
Upvotes: 2
Views: 260
Reputation: 9564
I ended up writing it like this:
let countAccepted = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Accepted" &&
data[i].BookingId == "0"
) {
this.multidropAccepted++;
}
}
};
Had to have it in the subscription block for it to work and defined before calling it. I called it at the end to make sure that my table has content in it as the first priority and only then counting these things
countAccepted(data)
This is how the whole thing looks:
constructor(
private adalService: AdalService,
private service: DeliveriesService,
private ngRedux: NgRedux<IAppState>
) {
this.service.getSectionAll();
this.sectionAllSubscription = this.sectionAll.subscribe(data => {
let countAccepted = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Accepted" &&
data[i].BookingId == "0"
) {
this.multidropAccepted++;
}
}
};
let countDelivered = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Delivered" &&
data[i].BookingId == "0"
) {
this.multidropDelivered++;
}
}
};
(this.dataSource = new MatTableDataSource(
data.filter(
(value, index, array) =>
!array.filter(
(v, i) => JSON.stringify(value) == JSON.stringify(v) && i < index
).length
)
)),
(this.dataSource.sort = this.sort),
(this.dataSource.paginator = this.paginator),
countAccepted(data);
countDelivered(data);
});
}
Upvotes: 1
Reputation: 3513
If you're using Angular with typescript then don't use function
keyword to write method. As it'll create its own scope & thus you'll not be able to access class level properties using this
inside it. Update your method code to:
countAccepted(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].DeliveryStatus == "Accepted" && arr[i].BookingId == "0") {
console.log("poop");
this.multidropAccepted++;
}
}
}
Upvotes: 2