按服务更改组件实例属性中的集时,角度生命周期挂钩需要什么?



我有一个组件发送到 MdDialog(我的自定义服务中的 Angular Material Dialog(

dialogRef = this.dialog.open(component, config);

当我通过组件实例更改此组件的公共属性时,如下所示:

dialogRef.componentInstance.task = task;

Angular 向我显示一个错误:

错误:表达式

已更改之后已检查错误:表达式在检查后已更改。以前的值:"未定义"。当前值:"对话框"。似乎视图是在对其父项及其子项进行脏检查后创建的。它是在更改检测钩子中创建的吗?

open-modal.service.ts 的完整代码

@Injectable()
export class TasksPopupService {
constructor(
private dialog: MdDialog,
private router: Router,
private tasksService: TasksService
) { }
public open(component: any, id?: string) {
if (id) {
this.tasksService.find(id)
.subscribe(task => {
this.bindDialog(component, task);
});
} else {
this.bindDialog(component, new Task());  
}
}
bindDialog(component, task: Task) {
let dialogRef;
let config = new MdDialogConfig();
config.height = '80%';
config.width = '70%';
dialogRef = this.dialog.open(component, config);
dialogRef.componentInstance.task = task;
dialogRef.afterClosed().subscribe(res => {
this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true });
});
return dialogRef;
}
}

但是只有当id未定义(在ELSE块中(时才会发生错误,我认为这是因为这个.tasksService.find返回可观察(异步(,而块ELSE不是异步的。但我不确定。

我在角度材料的MdContainer中遇到了一些令人困惑的错误。 如果我从服务器获取数据,则需要一些时间,但是当我传递一个新对象时,它发生得很快,如果我理解正确,更改检测不会完成。 此外,它不是父/子组件,生命周期钩子可能无法按我们的预期工作。
我找到了解决方案,但这是不对的。只是快速的解决方案。

if (id) {
this.tasksService.find(id)
.subscribe(task => {
this.bindDialog(component, task);
});
} else {
Observable.of(new Task()).delay(300).subscribe(task => {
this.bindDialog(component, task);
});
}

我使用延迟进行更改检测已完成,并且不会抛出错误。

最新更新