I am currently facing an issue with a component in my project. This component calls a service to retrieve locally stored JSON data, which is then mapped to an array of objects and displayed in the component view. The problem I am encountering is that the view bindings do not update properly the first time the service is called, but they do update correctly on subsequent calls.
Below is the template code for the component:
@Component({
selector: 'list-component',
template: `
<button type="button" (click)="getListItems()">Get List</button>
<div>
<table>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Job Title
</th>
</tr>
<tr *ngFor="let employee of _employees">
<td>
{{employee.id}}
</td>
<td>
{{employee.name}}
</td>
<td>
{{employee.jobTitle}}
</td>
</tr>
</table>
</div>
`,
changeDetection: ChangeDetectionStrategy.Default
})
Here is the controller class code for the component:
export class ListComponent {
_employees: Employee[];
constructor(
private employeeService: EmployeeService
) {
}
getListItems() {
this.employeeService.loadEmployees().subscribe(res => {
this._employees = res;
});
}
}
And here is the code for the service:
@Injectable()
export class EmployeeService {
constructor(
private http: Http
) { }
loadEmployees(): Observable<Employee[]> {
return this.http.get('employees.json')
.map(res => <Employee[]>res.json().Employees);
}
}
Some approaches I have tried so far include changing the ChangeDetectionStrategy
to OnPush
and making the _employees
property an observable. Despite trying various methods, the issue persists.
If anyone notices anything incorrect in my code or is aware of any potential RC6 issues that could be causing this behavior, please let me know. Thank you!