Угловой 5: «Не удается найти другой объект поддержки» [объект] в типе «объект».NgFor поддерживает только привязку к Iterables, таким как Arrays - PullRequest
0 голосов
/ 10 июня 2018

Я попытался найти ответы здесь, но не нашел ни одного, который можно было бы применить ко мне, вот и все. Я пытаюсь получить список занятий из .net бэкэнда, и все работает нормально, пока я не попытаюсь * NgForв представлении.
Я попытался добавить, например, 'employee.EmploymentList' к ответу, но затем я получил 'Свойство' Employmentlist 'не существует по типу' IListItem [] '

Это моеapp:

мой компонент списка, и я опубликую журнал консоли в нижней части сообщения.

export class EmployeeListComponent {

unitIdParam: string;
orgNoParam: string;
employeeList: EmployeeListItemComponent[];
errorMessage: string;


_ListFilter: string;
get listFilter(): string {
    return this._ListFilter;
}
set listFilter(value: string) {
    this._ListFilter = value;
    this.filteredEmployees = this.listFilter ? this.performFilter(this.listFilter) : this.employees;
}

@Input()
names: any[];

filteredEmployees: IListItem[] = [];
employees: IListItem[] = [];

constructor(elm: ElementRef, private apiService: ApiService, private route: ActivatedRoute) {
    this.names = elm.nativeElement.getAttribute('names');

    this.route.params.subscribe(params => {
        this.orgNoParam = params['orgNoParam'];
        this.unitIdParam = params['unitIdParam'];
    });
}

ngOnInit(): void {
    this.apiService.getEmploymentList(this.orgNoParam, this.unitIdParam)
        .subscribe(employees => {
            this.employeeList = employees;
            this.filteredEmployees = this.employeeList;
            console.log(this.filteredEmployees);
        },
        error => this.errorMessage = <any>error);
}

performFilter(filterBy: string): IListItem[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.employees.filter((employee: IListItem) =>
        employee.Name.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

}

мой сервис API

@Injectable()
export class ApiService {
//Set url
private employmentListUrl = 'api/employment/list';

constructor(private http: HttpClient) { }

getEmploymentList(orgNoParam: string, unitIdParam: string): Observable<IListItem[]> {
    //set headers
    let head = new HttpHeaders();
    head = head.append('Content-Type', 'application/json');

    //set params
    let params = new HttpParams();
    params = params.append('orgNoParam', orgNoParam);
    params = params.append('unitIdParam', unitIdParam);

    let data = {
        "orgNoParam": orgNoParam,
        "unitIdParam": unitIdParam
    };
    let body = JSON.stringify(data)

    //api call
    return this.http.post<IListItem[]>(this.employmentListUrl, body, { headers: head })
        .do(data => JSON.stringify(data))
        .catch(this.handleError);
}

private handleError(err: HttpErrorResponse) {
    console.log(err.message);
    return Observable.throw(err.message);
}

}

enter image description here

   </thead>
    <tbody>
        <tr class="gridrow" *ngFor="let employee of filteredEmployees">
            <td><input type="checkbox"></td>
            <td>
                {{employee.PersonKey._displayValue}}
            </td>
            <td>
                <a rel="popover" href="/{{ employee.EmploymentReference.OrganizationRegistrationNumber.FullValue }}/employment/{{ employee.EmploymentReference.NationalCivicRegistrationNumber.FullValue }}/info" class="name-employment new-style " data-parent-org-name="">{{employee.Name}}</a>
            </td>

enter image description here

enter image description here

1 Ответ

0 голосов
/ 10 июня 2018

Сама проблема в том, что типы, которые вы создали для себя, являются недействительными, потому что запрос от API возвращает что-то вроде {EmploymentList: IListItem[]}

Должно работать, если вы измените код в сервисе как

getEmploymentList(orgNoParam: string, unitIdParam: string): Observable<IListItem[]> {
...
//api call
return this.http.post<{EmploymentList: IListItem[]}>(this.employmentListUrl, body, { headers: head })
    .map(data => data.EmploymentList)
    .catch(this.handleError);
}

«Проблема» с машинописью заключается в том, что типы - это только ваше желание, а не что-то принудительное во время выполнения.Это особенно очевидно в коде, взаимодействующем с backend или около того - вы можете просто ожидать, что какой-то формат данных будет возвращен

EDIt: некоторое написание

...