У меня есть следующий метод, который возвращает число, и если это число больше 0, оно запрещает определенное действие:
checkAdded(name, forType, type) {
name = this.pipe.transform(name);
let count = 0;
if (type == "situation") {
Object.keys(this.dataSource3).forEach((key, index) => {
//console.log('Sit '+this.dataSource3.filteredData[index]['situation_type']+ ' '+name);
//console.log('Sit '+this.dataSource3.filteredData[index]['situation_for']+' '+forType);
if (this.dataSource3.filteredData[index]['situation_type'] == name && this.dataSource3.filteredData[index]['situation_for'] == forType) {
count++;
//console.log(count)
}
})
}
if (type == "legal") {
Object.keys(this.dataSource2).forEach((key, index) => {
console.log(this.dataSource2.filteredData[index]['legal_name']);
//console.log('L '+this.dataSource2.filteredData[index]['legal_name']+ ' '+name);
//console.log('L '+this.dataSource2.filteredData[index]['legal_for']+' '+forType);
if (this.dataSource2.filteredData[index]['legal_name'] == name && this.dataSource2.filteredData[index]['legal_for'] == forType) {
count++;
console.log(count)
}
})
}
if (type == "protection") {
Object.keys(this.dataSource).forEach((key, index) => {
if (this.dataSource.filteredData[index]['protection_name'] == name && this.dataSource.filteredData[index]['protection_for'] == forType) {
count++;
//console.log(count);
}
})
}
//console.log(count)
return count;
}
Если пользователь нажимает кнопку, указанную для типов situation
и protection
, checkAdded()
будет работать правильно.
Но если тип legal
, кнопка добавления выдаст следующую ошибку:
ОШИБКА TypeError: Не удается прочитать свойство 'legal_name' из undefined at protection.component.ts: 162 в Array.forEach () в ...
Источники данных:
dataSource = new MatTableDataSource<GetProtection[]>();
dataSource2 = new MatTableDataSource<GetLegal[]>();
dataSource3 = new MatTableDataSource<GetSituation[]>();
export interface GetProtection {
protection_name: string;
protection_date_added: string;
protection_status: string;
protection_for: number;
}
export interface GetLegal {
legal_name: string;
legal_date_added: string;
legal_status: string;
legal_for: number;
}
export interface GetSituation {
situation_name: string;
situation_date_added: string;
situation_status: string;
situation_for: number;
}
ЕслиЯ поддерживаю следующее:
if (type == "legal") {
Object.keys(this.dataSource2).forEach((key, index) => {
console.log(this.dataSource2.filteredData[index]['legal_name']);
if (this.dataSource2.filteredData[index]['legal_name'] == name && this.dataSource2.filteredData[index]['legal_for'] == forType) {
count++;
//console.log(count)
}
})
}
Он будет повторять все возможные значения legal_name
:
Итак, итерацияпроисходит, но внутри условия if
он не может найти legal_name
в массиве.
Если я утешу this.dataSource2
непосредственно перед выполнением итерации, он отобразит весь массив:
.
Существует метод установки всех трех dataSources
при нагрузке компонента:
this.dataSource = new MatTableDataSource(Object.values(data));
this.dataSource2 = new MatTableDataSource(Object.values(data2));
this.dataSource3 = new MatTableDataSource(Object.values(data3));
EDIT
Могу ли я использовать .every()
в случае type == 'legal'
?Но код будет похож на использование нескольких методов по одной и той же причине.