How to detect change from one component into other

前端 未结 2 424
甜味超标
甜味超标 2021-02-09 06:48

Angular 4. Github source

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

ngOnInit() {
             


        
2条回答
  •  情歌与酒
    2021-02-09 07:10

    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.

    You can read more about it here

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

    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

     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

     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.

提交回复
热议问题