如何检测从一个组件到另一个组件的更改

Val*_*Rob 6 typescript angular2-changedetection angular

Angular 4. Github来源

我有一个由Web服务填充的菜单.Web服务位于taskService中,但现在不是必需的.

ngOnInit() {
    this.getTasks();
    }
    getTasks(): void {
        this.taskService.getTasks()
            .subscribe(Tasks => this.tasks = Tasks);
    } 
Run Code Online (Sandbox Code Playgroud)

当您单击某个任务时,它会加载一个页面,一个不同的组件,表单已准备好更新数据.它也是由Web服务制作的,工作正常.问题是更新任务后,它没有反映在任务菜单中

我正在导入这个:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

并将其添加到构造函数:

private cdRef: ChangeDetectorRef
Run Code Online (Sandbox Code Playgroud)

在使用save()函数更新数据之后,这是我对detectChanges()函数的最佳方法

  this.taskService.updateTask(task, id)
          .subscribe(
              this.Ref.detach();
              setInterval(() => {
                this.Ref.detectChanges();
              }, 5000);
      );
Run Code Online (Sandbox Code Playgroud)

这是从菜单中打印任务的html:

   <li *ngFor="let task of tasks" class="d-inline-block col-md-12">
        <a routerLink="/task/{{task.id}}" > {{task.title}}</a>
        <!-- <span class="close big"></span> -->
        <button class="close big" title="delete task"
        (click)="delete(task)">x</button>
    </li>
Run Code Online (Sandbox Code Playgroud)

这是更新任务的表单

<form (ngSubmit)="save(taskName.value, taskBody.value)" #taskForm="ngForm" class="example-form">
  <mat-form-field class="example-full-width">
    <label>Task Name</label>
    <input matInput [(ngModel)]="task.name" #taskName name="name">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput [(ngModel)]="task.body" #taskBody name="body"></textarea>

  </mat-form-field>
  <button type="submit" class="btn btn-success" >Save</button>
</form>
Run Code Online (Sandbox Code Playgroud)

两者都有不同的组成部分.

我试过按照本教程,但我卡住了,我不知道如何使用ChangeDetectorRef.

Bun*_*ner 5

我看过你的代码。问题在于view-task.component更新了您的任务,但未navigation.component通知此事务。我认为这BehaviorSubject可能只是适合您的事情。

您可以在这里了解更多信息

我假设您将tasks在整个应用程序中使用一个数组,并将它们显示在navigation组件上。

Task.service.ts

export class TaskService {
     // behaviorSubject needs an initial value.
     private tasks: BehaviorSubject = new BehaviorSubject([]);
     private taskList: Task[];

     getTasks() {
         if (!this.taskList || this.taskList.length === 0) {
             this.initializeTasks();
         }

         return this.tasks.asObservable();
     }

     initializeTasks() {
          this.http.get('api/tasks')
              .subscribe(tasks => {
                   // next method will notify all of the subscribers
                   this.tasks.next(tasks);
              }, error => {
                   // proper error handling here
              });
     }

     updateTasks(task: Task) {
          this.http.post('api/updateTask')
              .subscribe(resp => {
                   // update your tasks array
                   this.tasks = ...
                   // and call next method of your behaviorSubject with updated list
                   this.tasks.next(this.tasks);
              }, error => {
                   // proper error handling here    
              });
     }
}
Run Code Online (Sandbox Code Playgroud)

Navigation.component.ts

 export class NavigationComponent implements OnInit{
      tasks: Task[];
      constructor(private taskService: TaskService) {}

      ngOnInit() {
          // this method will be called every time behaviorSubject
          // emits a next value.
          this.taskService.getTasks()
              .subscribe(tasks => this.tasks = tasks);
      }
 }
Run Code Online (Sandbox Code Playgroud)

View-task.component.ts

 export class ViewTaskComponent {
     constructor(private taskService: TaskService) {}

     updateTask(task: Task) {
         this.taskService.updateTask(task);
     }
 }
Run Code Online (Sandbox Code Playgroud)

我自己还没有尝试过此代码。但是,我之前在我的应用程序上实现了类似的功能。因此,当您尝试并遇到问题时,请告诉我。