【问题标题】:Angular 2: update list component from form component siblingAngular 2:从表单组件兄弟更新列表组件
【发布时间】: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


【解决方案1】:

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

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

不同之处在于 Angular 服务调用的 Web api 调用。似乎要使完成回调重新触发,必须从 API 返回某些内容。

在编辑案例中,我没有返回任何内容,只返回一个 HTTP.OK,但是当我将其更改为返回一个用户对象时,回调会触发,并且列表会更新。在我看来,在某处写下来是一件好事,所以我将它提供给后代,希望它可以为某人节省一些悲伤。

【讨论】:

    猜你喜欢
    • 2016-06-23
    • 1970-01-01
    • 2019-04-16
    • 2019-09-17
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多