Angular 2 Sibling Component Communication

前端 未结 12 1302
深忆病人
深忆病人 2020-11-22 06:31

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so

12条回答
  •  死守一世寂寞
    2020-11-22 07:02

    Behaviour subjects. I wrote a blog about that.

    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    private noId = new BehaviorSubject(0); 
      defaultId = this.noId.asObservable();
    
    newId(urlId) {
     this.noId.next(urlId); 
     }
    

    In this example i am declaring a noid behavior subject of type number. Also it is an observable. And if "something happend" this will change with the new(){} function.

    So, in the sibling's components, one will call the function, to make the change, and the other one will be affected by that change, or vice-versa.

    For example, I get the id from the URL and update the noid from the behavior subject.

    public getId () {
      const id = +this.route.snapshot.paramMap.get('id'); 
      return id; 
    }
    
    ngOnInit(): void { 
     const id = +this.getId ();
     this.taskService.newId(id) 
    }
    

    And from the other side, I can ask if that ID is "what ever i want" and make a choice after that, in my case if i want to delte a task, and that task is the current url, it have to redirect me to the home:

    delete(task: Task): void { 
      //we save the id , cuz after the delete function, we  gonna lose it 
      const oldId = task.id; 
      this.taskService.deleteTask(task) 
          .subscribe(task => { //we call the defaultId function from task.service.
            this.taskService.defaultId //here we are subscribed to the urlId, which give us the id from the view task 
                     .subscribe(urlId => {
                this.urlId = urlId ;
                      if (oldId == urlId ) { 
                    // Location.call('/home'); 
                    this.router.navigate(['/home']); 
                  } 
              }) 
        }) 
    }
    

提交回复
热议问题