问题描述
使用 TypeScript 和 Angular,我试图在我的 testConnection 函数中创建一个空数组,允许每次调用该函数时添加对象,而无需清除数组。
测试连接函数:
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));
}
目前,按照我的逻辑,它将系统对象添加到数组中,但由于空数组声明在函数内,因此每次调用函数时都会清除并重新启动此过程。我试图在类的顶部声明 systemList (systemList = any[]),但是当我尝试在函数中引用它时,它显示为未定义。
如何在调用函数时随时将系统对象添加到数组中,而无需从数组中清除现有对象?
解决方法
您应该能够在函数之外设置一个组件变量,然后列表将保持不变。
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 {}
}
另一种选择是创建一个服务并使用该服务来保存系统列表的状态,如果您希望多个组件访问系统列表,这将更有用。
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() {}
}
那么你的 testConnection 函数会像这样使用它。
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)
)
}