且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测从一个组件到另一个组件的变化

更新时间:2023-01-08 18:48:57

我看过您的代码.问题是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.