Handling Error: "Provided data source did not match an array, Observable, or DataSource" in Angular

130 Views Asked by At

I faced an issue with handling errors.

Error isn't caught because I got different response for getting existing record and different for the record which doesn't exist.

I got error in these two components in "subscribe()":

export class TableViewComponent implements OnInit, OnDestroy {
  private subscribe$: Subject<void> = new Subject<void>();
  columns: string[] = ['name', 'description', 'isCompleted'];
  tasks: ToDoTask[] = [];
  currentlySelectedTable: DefaultTable = {};

  constructor(private toDoTasksService: ToDoTasksService, private activeTableService: ActiveTableService) {
    this.activeTableService.activeTable.subscribe(selectedTable => {
      this.currentlySelectedTable = selectedTable;
      this.getTasks();
      this.refreshTable();
    });
  }

  ngOnInit() { }

  getTasks() {
    this.toDoTasksService
      .tasksGet(this.currentlySelectedTable.id)
      .pipe(takeUntil(this.subscribe$))
      .subscribe({
        next: (tasks: ToDoTask[] | any) => {
          if (!Array.isArray(tasks)) {          
            tasks as any;            
            throw Error(tasks.title);
          } else {
            this.tasks = tasks;                    
          }          
        },
        error: (error) => {
          console.error(error);
        },
      });
  }
export class TablesListComponent implements OnInit, OnDestroy {
  private subscribe$: Subject<void> = new Subject<void>();
  tables: DefaultTable[] = [];

  constructor(private tableService: TablesService, private activeTableService: ActiveTableService) {}

  ngOnInit() {
    this.tableService
      .tablesGet()
      .pipe(takeUntil(this.subscribe$))
      .subscribe({
        next: (tables: DefaultTable[]) => {
          this.tables = tables;
        },
        error: (error: any) => {
          console.error(error);
        },
      });
  }

  tableElementClicked(event: MouseEvent) {
    const htmlElement: HTMLParagraphElement = event.currentTarget as HTMLParagraphElement;

    this.tables.forEach(table => {
      if (table.name === htmlElement.textContent) {
        this.activeTableService.activeTable.next(table);
        
        return;
      }
    });
  }

  ngOnDestroy() {
    this.subscribe$.unsubscribe();
  }
}

Response for table with Id that exists:

enter image description here

Response for table with Id that doesn't exist:

enter image description here

The Status Code from backend for both cases is OK = 200.

Used services are auto-generated by OpenAPI Generator and there is info that not to edit the class manually.

I have checked SO for similar issues but none of them seems to be helpful in my case but maybe I missed something.

Thanks for any help or advice.

EDIT:

I have edited getTasks() method and get almost safisfying result in DevTools/Console:

enter image description here

0

There are 0 best solutions below