The view does not refresh when the properties of a component change in Angular 2 RC6 for the first time

I have a component in my project that calls a service to retrieve some (locally stored) JSON that maps to an array of objects and returns to the displayed component. The problem I am facing is that the bindings in the view do not seem to update when the service is first called, but update the second time I call the service.

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

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 tried:

  • Change ChangeDetectionStrategytoOnPush
  • Creating an _employeesobservable property , filling it this._employees = Observable<Employee[]>and using the asynchronous channel in the ngFor statement: *ngFor="let employees of _employees | async"- the same situation, only filled with the second button

- - - RC6, ?

+4
1

. . detectChanges . , , .

export class ListComponent {

_employees: Employee[];

constructor(
    private employeeService: EmployeeService,  private chRef: ChangeDetectorRef
) {

}

getListItems() {
    this.employeeService.loadEmployees().subscribe(res => {
        this._employees = res;
        this.chRef.detectChanges()
    });
}

}

+2

Source: https://habr.com/ru/post/1654440/


All Articles