angular - View 不会第一次更新 Angular 2 RC6 中的组件属性更改

标签 angular typescript

我的项目中有一个组件调用一个服务来检索一些(本地存储的)JSON,它被映射到一个对象数组并返回到要显示的组件。我遇到的问题是 View 中的绑定(bind)在我第一次调用该服务时似乎没有更新,但在我第二次调用该服务时确实更新了。

组件模板:

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

组件 Controller 类:

export class ListComponent {

    _employees: Employee[];

    constructor(
        private employeeService: EmployeeService
    ) {

    }

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

和服务:

@Injectable()
export class EmployeeService {

    constructor(
        private http: Http
    ) { }

    loadEmployees(): Observable<Employee[]> {
        return this.http.get('employees.json')
         .map(res => <Employee[]>res.json().Employees);
    }
}

我尝试过的事情:

  • 更改 ChangeDetectionStrategyOnPush
  • 制作_employees属性是一个可观察的,用 this._employees = Observable<Employee[]> 填充它并在 ngFor 语句上使用异步管道:*ngFor="let employees of _employees | async" - 同样的情况,只在第二次点击按钮时填充

谁能发现我的代码有什么问题,或者知道 RC6 的任何问题都可能导致这种行为?

最佳答案

我有同样的问题。仍然没有得到任何可靠的解决方案。使用 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()
    });
}

关于angular - View 不会第一次更新 Angular 2 RC6 中的组件属性更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39466630/

相关文章:

javascript - 如何在 TypeScript 中声明函数的返回类型

angular - 如何在 Angular 中转义大括号

javascript - 我如何使用 pdfjs-dist 和 Angular 修复此错误消息?

javascript - Angular2 服务返回未定义

javascript - 在 Angular 2 中加载 jQuery 函数

Angular 5 订阅和取消订阅 Observable

javascript - typescript :类型 'string' 不可分配给类型 '"数字"| "2-digit"' 在 Date::toLocaleDateString()

css - <div (click) ="handler()"> 在 edge 中不起作用,但在 IE11 和其他浏览器中起作用

angular - 模拟对象如何在 Angular jasmine 单元测试中工作

javascript - 未能以 react 形式在 'value' 上设置 'HTMLInputElement' 属性