Search code examples
javascriptangularobservable

Angular: How can i push an observable to a list


I get an Error message that i cant push an undefined variable to my list. This is my code in the component.ts

for (const file of this.allFiles) {
  this.uploadFileService
    .validate(file)
    .subscribe(  valid => {
      this.validList.push(valid);
    })
}

This is my Service:

validate(file: File): Observable<boolean> {
      const data: FormData = new FormData();
      data.append('file', file);
      return this.http.post<boolean>(`${this.url}/validate`,data);
    }

How can I push to the list?


Solution

  • You will get this error if you do not initialize the array ([]) first before pushing. Please declare the variable validList: Array<any> = [] at the top of the component before pushing data inside.

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit{
      name = 'Angular';
      validList: Array<any> = [];
    
      ngOnInit() {
        this.validList.push(true);
      }
    }
    

    Issue replicated stackblitz

    Working stackblitz