I have a component in my project that calls a service to retrieve some (locally-stored) JSON, which is mapped to an array of objects and returned to the component to be displayed. The problem I am having is that the bindings in the view don't seem to update the first time I call the service, but do update the second time I call the service.
The component template:
@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
})
The component controller class:
export class ListComponent {
_employees: Employee[];
constructor(
private employeeService: EmployeeService
) {
}
getListItems() {
this.employeeService.loadEmployees().subscribe(res => {
this._employees = res;
});
}
}
And 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);
}
}
Things I've tried:
ChangeDetectionStrategy
to OnPush
_employees
property an observable, populating it with this._employees = Observable<Employee[]>
and using the async pipe on the ngFor statement: *ngFor="let employees of _employees | async"
- same situation, only populates on second button click Can anyone spot anything wrong with my code, or are aware of any issues with RC6 that could lead to such behaviour?
I had same issue. Still didn't get any solid solution. Using detectChanges
works. Below is the workaround but please note that this is not the perfect solution
export class ListComponent {
_employees: Employee[];
constructor(
private employeeService: EmployeeService, private chRef: ChangeDetectorRef
) {
}
getListItems() {
this.employeeService.loadEmployees().subscribe(res => {
this._employees = res;
this.chRef.detectChanges()
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.