【发布时间】:2017-04-01 19:41:21
【问题描述】:
我有一个父组件,控制两个子组件。 FormChild 是一种将教师添加到列表并对其进行编辑的输入表单,ListChild 是使用 FormChild 输入/编辑的教师列表。所需的行为(我只是部分工作)是在 ListChild 中反映 FormChild 中的更改。
FormChild 有两种模式;编辑和添加。标志确定表单是否具有“添加”值或“编辑”值。标志(编辑)为真时调用'editTeacher'服务方法,为假时调用'addTeacher'服务方法。
public emitChangeNotification() {
this.changeNotifier.emit();
}
teacherAddEdit(event) {
if (!this.editing) {
this._userService.addTeacher(this.userItem)
.subscribe(
nextItem=> this.nextItemMsg = nextItem
, error => this.errorMsg = <any> error
, ()=>this.emitChangeNotification()
);
}
else {
this._userService.editTeacher(this.userItem)
.subscribe(
nextItem=> this.nextItemMsg = nextItem
, error => this.errorMsg = <any> error
, ()=>this.emitChangeNotification()
);
}
this.initForm();
}
请注意,在添加和编辑情况下,对服务的调用几乎相同。这里应该发生的是,在完成时,observable 将调用 this.EmitChangeNotification,它会冒泡到父级,然后导致 ListChild 更新。
问题是,ListChild 仅在添加时更新,而不是在编辑时更新!使用 f12 跟踪代码,我看到在“添加”的情况下,this.EmitChangeNotification 被调用;但不是在编辑案例中。这只是 web ui 的问题;后端被调用,更改被保存在数据库中就好了。
服务中的服务调用是相同的,只是调用了特定的后端web api方法:
addTeacher(userToCreate:CreateUser)
{
let Url = this.BASEURL + '/accounts/create';
let headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(userToCreate);
return this._http.post(this._createUserUrl, body, options).map((res: Response) => res.json());
}
editTeacher(userToChange:CreateUser)
{
let Url = this.BASEURL + '/updateTeacher/' + userToChange.UserId;
let headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(userToChange);
return this._http.post(Url, body, options).map((res: Response) => res.json());
}
最初,服务中的“editTeacher”使用的是_http.put;我将其更改为 _http.post;但这没有帮助。我看过一些例子;似乎这应该可以工作......我做错了什么?
提前致谢
编辑: 另一个线索......似乎在“编辑”情况下根本没有调用订阅的“完成”回调。我替换了:
, ()=>this.emitChangeNotification()
与
, ()=>console.log('tell someone')
并且日志在添加时显示消息但在编辑时不显示。
我看不出它们有什么不同...
【问题讨论】:
-
你怎么知道在编辑时
emitChangeNotification没有被调用?你收到任何错误吗? -
我可以通过在 chrome 上使用 f12 单步执行代码来查看它。我没有将 changeNotifier.Emit() 直接作为订阅的第三个参数,而是编写了单独的函数 emitChangeNotification()。我在那个函数上设置了断点,添加时断点,但编辑时没有。
标签: angular components refresh observable siblings