dgk*_*ane 7 typescript angular
我的项目中有一个组件调用一个服务来检索一些(本地存储的)JSON,它被映射到一个对象数组并返回给要显示的组件.我遇到的问题是视图中的绑定似乎在我第一次调用服务时没有更新,但是第二次调用服务时会更新.
组件模板:
@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
})
Run Code Online (Sandbox Code Playgroud)
组件控制器类:
export class ListComponent {
_employees: Employee[];
constructor(
private employeeService: EmployeeService
) {
}
getListItems() {
this.employeeService.loadEmployees().subscribe(res => {
this._employees = res;
});
}
}
Run Code Online (Sandbox Code Playgroud)
和服务:
@Injectable()
export class EmployeeService {
constructor(
private http: Http
) { }
loadEmployees(): Observable<Employee[]> {
return this.http.get('employees.json')
.map(res => <Employee[]>res.json().Employees);
}
}
Run Code Online (Sandbox Code Playgroud)
我试过的事情:
ChangeDetectionStrategy为OnPush_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()
});
}
Run Code Online (Sandbox Code Playgroud)
}