Angular2 - redirection after sending does not display updated data

I have the following component that has two input and submit fields. After sending, the data is sent to the server, and the page is redirected to the task page.

But the data on this page is not updated, since the task page should receive data from the database.

if I refresh the page or move back and forth. Updated data is visible.

@Component({ selector: 'edit-tasks', template: `<div mdl class="mdl-grid demo-content"> <div class="demo-graphs mdl-shadow--2dp mdl-color--white mdl-cell mdl-cell--8-col"> <h3>EDIT Task Page</h3> <form action="#" (ngSubmit)="onSubmit()"> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <input class="mdl-textfield__input" type="text" id="taskname" [(ngModel)]="data.taskname"/> <label class="mdl-textfield__label" for="taskname">Task Name</label> </div> <br/> <div class="mdl-textfield mdl-js-textfield"> <textarea class="mdl-textfield__input" type="text" rows= "5" id="taskdesc" [(ngModel)]="data.taskdesc"></textarea> <label class="mdl-textfield__label" for="taskdesc">Task Description</label> </div> <br/> <br/> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit">SAVE</button> </form> </div> `, directives: [ROUTER_DIRECTIVES, MDL] }) export class EditTaskComponent { data: any; constructor(private apartmentService: ApartmentService,private router: Router, private sharedService: SharedService) { this.data=this.sharedService.temp; console.log(JSON.stringify(this.data)); } onSubmit(form) { this.apartmentService.updateTask(this.data); this.router.navigate(['Tasks']); } } 

Günter Zöchbauer update

  onSubmit(form) { this.apartmentService.updateTask(this.data).then(_=>this.router.navigate(['Tasks'])); <-- changed this as per @Günter Zöchbauer suggestion and it works :) this.router.navigate(['Tasks']); } 

In service.ts

 updateTask(data:any){ return new Promise((resolve,reject)=> { this.http.put(`./api/newtask/${data._id}`, JSON.stringify(data),{ headers: new Headers({'Content-Type':'application/json'}) }) .map((res: Response) => res.json()).subscribe(data => {resolve(data)}, error => reject(error)) }); } 

How can I handle this through observables? Can I avoid promises?

+2
source share

Source: https://habr.com/ru/post/1265283/


All Articles