Angular 2: 从表单组件兄弟更新列表组件

Angular 2: update list component from form component sibling

我有一个父组件,控制着两个子组件。 FormChild 是一个输入表单,可以将教师添加到列表并对其进行编辑,ListChild 是 input/edited 使用 FormChild 的教师列表。所需的行为(我只是部分工作)是在 ListChild 中反映 FormChild 中的更改。

FormChild 有两种模式;编辑和添加。标志确定表单是否具有 'add' 值或 'edit' 值。当标志(编辑)为真时,调用'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 跟踪代码,我看到在 'add' 的情况下, this.EmitChangeNotification 被调用;但不在编辑案例中。这只是网络的问题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;但这没有帮助。我看过很多示例;看起来这应该可以正常工作...我做错了什么?

提前致谢

编辑: 另一个线索...似乎在 'edit' 情况下根本没有调用订阅的 'on complete' 回调。我替换为:

, ()=>this.emitChangeNotification()

, ()=>console.log('tell someone')

并且日志在添加 时显示消息,但在编辑时不显示

我看不出它们有什么不同...

要回答我自己的问题....

事实上,网络 ui 并没有什么不同。

区别在于 Web api 调用是 angular 服务调用。看来要让完成回调触发必须发生的事情是必须从 API 编辑某些内容。

在编辑案例中,我 return 什么都没有,只有 HTTP.OK,但是当我将其更改为 return 用户对象时,回调将触发,并且列表已更新。在我看来,把它写下来是一件好事,所以我在这里提供给后代,希望它能减轻一些人的悲伤。