I have the method getAllDates
that appends (inside the next
handler) all the schedule dates from the server to class scope array variable this.futureScheduleDateStrings
. My question is – should I initialize that array to empty content before subscribe
method or at the beginning of the next
handler – I have noticed that if I initialize it before subscribe
it has some duplicates values.
getAllDates() {
this.futureScheduleDateStrings = [];
this.accountService.getAllDates()
.pipe(first())
.subscribe({
next: (value: ScheduleDateTimes) => {
//this.futureScheduleDateStrings = [];
this.scheduleDateTime = value.scheduleDateTimes;
...
},
error: error => {
console.log();
}
});
3
Answers
I think I have found the problem. Two immediate attempts to call the
subscribe
one after another initialize twice the variablefutureScheduleDates
to empty array.Then each
subscribe
is called and no initialization is happening anymore - that is why there is duplicate. The only solution I see is to initialize this variable inside thenext
handler. I don't have anything like mutext like in c#/c++. Is there any other fix for that problem?In Angular, it’s generally a good practice to initialize class variables before you enter asynchronous operations like
HTTP
requests. In your case, it’s better to initialize thethis.futureScheduleDateStrings
array before the subscribe method.You might be experiencing double execution because of the double click on a button that calls
getAllDates
method. TrydebounceTime(300)
to prove it.Also you don’t need
first
if you are working solely with HTTP requests. Observable will automatically complete after the request is done.Regarding the initialization of
futureScheduleDateStrings
: you have to initialize it immediately (either with property initializer or in type’s constructor). Enable ESLint with recommended rules for your app and you won’t need to ask such questions here, it will report all problems in your code immediately.