How to create an empty array within a TypeScript function, and add objects to it every time the function is called

Viewed 45

Using TypeScript and Angular, I am trying to create an empty array within my testConnection function that allows the addition of objects every time the function is called, without clearing the array.

testConnection function:

  testConnection(system) {
    var systemList = [];
    this.service.testConnection(system)
      .subscribe(conn => {
        if (conn == 'Success') {
          this.snackBarHandler.open('Connection Found', 'success');
          system.isClicked = false;
          system.connection = true;
          systemList.push(system);
        }
        else {
          this.snackBarHandler.open('Connection Failed', 'failure');
          system.isClicked = false;
          system.connection = false;
          systemList.push(system);
        }
      }, err => console.log(err));
  }

Currently, with the logic I have, it is adding the system object to the array, but since the empty array declaration is within the function, it is clearing and restarting this process every time the function is called. I have tried to declare the systemList at the top of the class (systemList = any[]), but when I try to reference it within the function, it is showing up as undefined.

How am I able to add system objects to the array any time the function is called, without clearing the existing objects out of the array?

1 Answers

You should be able to set a component variable outside of the function, then the list will persist.

export class SystemComponent implements OnInit {

  constructor(private service: TestConnectionService) {}

  systemList = []

  testConnection(system) {
    this.service.testConnection(system)
      .subscribe(conn => {
        this.systemList.push(system);
        if (conn === 'Success') {
          this.snackBarHandler.open('Connection Found', 'success');
          system.isClicked = false;
          system.connection = true;
        }
        else {
          this.snackBarHandler.open('Connection Failed', 'failure');
          system.isClicked = false;
          system.connection = false;
        }
      }, err => console.log(err));
  }
  ngOnInit(): void {}
}

Another option is to create a service and use the service to hold the state of the system list which is more useful if you want multiple components to access the systemList.

interface System {
  some: string
  props: string
}

@Injectable({ providedIn: 'root' })
export class SystemService {
  private _systemList$$ = new BehaviorSubject<System[]>([])


  get systemList(): System[] {
    return this._systemList$$.value
  }

  addToSystemList(system: System) {
    this._systemList$$.next([...this.systemList, system])
  }

  constructor() {}
}

then your testConnection function would use it like this.

testConnection(system) {
  this.service.testConnection(system).subscribe(
    conn => {
      this.systemService.addToSystemList(system)
      if (conn === 'Success') {
        this.snackBarHandler.open('Connection Found', 'success')
        system.isClicked = false
        system.connection = true
      } else {
        this.snackBarHandler.open('Connection Failed', 'failure')
        system.isClicked = false
        system.connection = false
      }
    },
    err => console.log(err)
  )
}
Related