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() {
this.getTasks();
}
getTasks(): void {
this.taskService.getTasks()
.subscribe(Tasks => this.tasks = Tasks);
}
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
I am importing this:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
and adding this to the constructor:
private cdRef: ChangeDetectorRef
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);
);
This is the html from the menu to print the tasks:
<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>
And this is the form that updates the task
<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.
I have tried to follow this tutorial, but I'm stuck, I don't know how to use the ChangeDetectorRef.
changeDetection
manually. Angular should be able to pick it up when you updatetasks
. Do you setchangeDetectionStrategy
in yourComponent
declaration? – Hetaerathis.tasks
in your subscribe callback is being redefined with the updated data from the form submission? – HaddixupdateTask()
in the view.task component, I did aconsole.log
there, in the menu component, to see if something change, but no, my console log show me old data. @Haddix – HabitueupdateTask()
finishes, it's returned tosave()
in yourViewTaskComponent
, but there is no link tothis.task
in the subscription callback tothis.taskService.updateTask()
. SinceupdateTask
uses a PATCH request, I'm assuming you're not getting the wholeTask
object back. So you won't be able to just saythis.task = valuePassedToSubscribeCallback
. Instead you can invokethis.viewTask()
in that subscribe callback and fetch the entire updatedTask
object. – Haddixthis.viewTask()
? in thesave()
function, inside theupdatetask
? @Haddix – HabitueupdateTask
. – Haddix