skip to Main Content

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


  1. Chosen as BEST ANSWER

    I think I have found the problem. Two immediate attempts to call the subscribe one after another initialize twice the variable futureScheduleDates 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 the next handler. I don't have anything like mutext like in c#/c++. Is there any other fix for that problem?


  2. 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 the this.futureScheduleDateStrings array before the subscribe method.

    getAllDates() {
        this.futureScheduleDateStrings = []; // Initialize the array here
    
        this.accountService.getAllDates()
          .pipe(first())
          .subscribe({
            next: (value: ScheduleDateTimes) => {
              this.scheduleDateTime = value.scheduleDateTimes;
    
              // Populate this.futureScheduleDateStrings with data from the subscription
              // ...
            },
            error: error => {
              console.log();
            }
          });
    }
    
    Login or Signup to reply.
  3. You might be experiencing double execution because of the double click on a button that calls getAllDates method. Try debounceTime(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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search