0

I have tried looking for answers in here, but havent found any that can be applied to me so here goes.I am trying to get a list of employments from .net backend and everyting is working fine until i try to *NgFor in the view.
I have tried adding for example 'employees.EmploymentList' to the response, but then I get 'Property 'Employmentlist' does not exist on type 'IListItem[]'

This i my app:

my list component, and ill post the console log in the bottom of the post.

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);
}

}

my api service

@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

5
  • Can you please add the HTML where you creating your ngFor? The issue seems that be that the value you're passing is not an array. It might help if you could show us the JSON you're working with as well. Commented Jun 10, 2018 at 8:37
  • Shouldn't you use json.parse, in the do operator, in the http.post stream ? Commented Jun 10, 2018 at 8:44
  • well, i followed a tutorial that made it work doing this, and when I try json.parse it gives me 'Argument of type 'IListItem[]' is not assignable to parameter of type 'string''... Commented Jun 10, 2018 at 8:48
  • 1
    Ok , something else i noticed, isn't it more accurate for your fitler.employees=this.employeeList.EmploymentList , because now it seems that you are passing an object to the ng for, not an array. Commented Jun 10, 2018 at 9:01
  • I tried it, but it gives 'Property 'EmploymentList' does not exist on type 'EmployeeListItemComponent[]'. Wich is not that strange. Whats happening is, in the api service i map the response to IListItem[] which looks exactly like EmployeeListItemComponent. Then in employee.list.component I make employeeList an array of EmployeeListItemComponent as you can see in the top of the post. I added an image of the EmployeeListItemComponent. Sry for the confusion! Commented Jun 10, 2018 at 9:11

1 Answer 1

2

The very problem is that the types you have made for yourself are invalid because the request from api returns something like {EmploymentList: IListItem[]}

Should be working if you modify the code within the service as

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);
}

The "problem" with typescript is, that types are just your wish, not something enforced by runtime. This is especialy obvious in code interfacing with backend or so - you may just expect some format of data being returned

EDIt: Some spelling

Sign up to request clarification or add additional context in comments.

3 Comments

When I paste this it gives me two errors: on '.map' : (TS) Property 'map' does not exist on type 'Observable<{ EmploymentList: IListItem[]; }>' and on 'data': (TS) Parameter 'data' implicitly has 'any' type...
If map is not defined on observable, you have to add `import 'rxjs/add/operator/map' to the begining of your file
Another question if you have the time, pls. Lets say I want to also have "TotalCount: number" in that post. The class I am returning har ApiModel.EmploymentList and ApiModel.TotalCount. Do you know how to get both of these?...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.