如何检测从一个组件到另一个组件的变化 [英] How to detect change from one component into other

查看:101
本文介绍了如何检测从一个组件到另一个组件的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular4. Github源码

Angular 4. Github source

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

I have a menu which is filled by a web service. The web service is in taskService, but is not necessary now.

ngOnInit() {
    this.getTasks();
    }
    getTasks(): void {
        this.taskService.getTasks()
            .subscribe(Tasks => this.tasks = Tasks);
    } 

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

When you click on a task it loads a page, a different component, with a form ready to update the data. It is also made by a web service and works fine. The problem is that after update the task, it is not reflected in the task menu

我正在导入:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

并将其添加到构造函数中:

and adding this to the constructor:

private cdRef: ChangeDetectorRef

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

And this is my best approach to the detectChanges() function, after update the data with the save() function

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

这是菜单中用于打印任务的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>

这是更新任务的表单

<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>

两者都在不同的组件中.

Both are in different components.

我尝试遵循此教程,但我被困住了,我不知道如何使用ChangeDetectorRef.

I have tried to follow this tutorial, but I'm stuck, I don't know how to use the ChangeDetectorRef.

推荐答案

我看过您的代码.问题是view-task.component更新了您的任务,但是navigation.component没有收到有关此事务的通知.我认为BehaviorSubject可能只是适合您的事情.

I've looked at your code. The problem is that the view-task.component updates your tasks, but the navigation.component is not notified about this transaction. I think BehaviorSubject might be just the thing for you.

您可以在此处

我假设您在整个应用程序中只有一个tasks数组,并将其显示在navigation组件上.

I assume you would have single array of tasks throughout your application and you would display them on your navigation component.

Task.service.ts

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    
              });
     }
}

Navigation.component.ts

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);
      }
 }

View-task.component.ts

View-task.component.ts

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

     updateTask(task: Task) {
         this.taskService.updateTask(task);
     }
 }

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

I haven't tried this code myself. However, I have implemented something similar on my application before. So when you try it and have a problem, let me know.

这篇关于如何检测从一个组件到另一个组件的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆