ValRob
ValRob

Reputation: 2692

Bind data from a different controller in Angular

In angular 4.

I have navbar, a menu component with different tasks. This task comes from a web service.

When I click on one of these task from the menu, it calls the edit task component, with a form on it.

The data from the form of the edit task is bind to some fields from the component of Edit task, so when I change something in the form, it is reflected in the header of the form.

But the data from menu component don't change. How can I update/bind the data in the menu component? I don't want to refresh the page. Maybe the solution is calling the getTasks() function, but that have to be done in the edittask component

menu.component.ts here i call the list of tasks:

ngOnInit() {
    this.getTasks();
}

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

menu.component.html here i call the task list:

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

after filling the form from the edit task I call the function onSubmit() for call the webservice:

this.taskService.updateTask(task, id)
      .subscribe(
        // i need to refresh the getTask that is in the menu. 
        // or do something for update the menu task
        );

Upvotes: 0

Views: 134

Answers (2)

AVJT82
AVJT82

Reputation: 73367

You could use a subject to tell the menu component to refetch the data, so in menu component declare a subject and listen to any next:

import { Subject } from 'rxjs/Subject';

// ...

public static updateTasks: Subject<boolean> = new Subject();

constructor(...) {
  MenuComponent.updateTasks
    .subscribe(res => {
       this.getTasks();
    })
}

and then in the component where you edit the task, just call next on the subject to tell the menu component to execute getTasks:

import { MenuComponent } from '....'

// ...

this.taskService.updateTask(task, id)
    .subscribe(() => MenuComponent.updateTasks.next(true));

Upvotes: 1

user9117694
user9117694

Reputation:

If you add Detect change in your menu component ?

ngAfterViewChecked() {

    this.cdRef.detectChanges();

}    

And import :

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

and add this to constructor param :

private cdRef: ChangeDetectorRef

Upvotes: 0

Related Questions