
Saving the workout
The workout that we are building needs to be persisted (in-memory only). The first thing that we need to do is extend WorkoutService and WorkoutBuilderService.
WorkoutService needs two new methods, addWorkout and updateWorkout:
addWorkout(workout: WorkoutPlan){ if (workout.name){ this.workouts.push(workout); return workout; } } updateWorkout(workout: WorkoutPlan){ for (var i = 0; i < this.workouts.length; i++) { if (this.workouts[i].name === workout.name) { this.workouts[i] = workout; break; } } }
The addWorkout method does a basic check on the workout name and then pushes the workout into the workout array. Since there is no backing store involved, if we refresh the page, the data is lost. We will fix this in the next chapter where we persist the data to a server.
The updateWorkout method looks for a workout with the same name in the existing workouts array and if found, updates and replaces it.
We only add one save method to WorkoutBuilderService as we are already tracking the context in which workout construction is going on:
save(){ let workout = this.newWorkout ? this._workoutService.addWorkout(this.buildingWorkout) : this._workoutService.updateWorkout(this.buildingWorkout); this.newWorkout = false; return workout; }
The save method calls either addWorkout or updateWorkout in the Workout service based on whether a new workout is being created or an existing one is being edited.
From a service perspective, that should be enough. Time to integrate the ability to save workouts into the Workout component and learn more about the form directive!
Before we look at NgForm in more detail, let's add the save method to Workout to save the workout when the Save button is clicked on. Add this code to the Workout component:
save(formWorkout:any){ if (!formWorkout.valid) return; this.workoutBuilderService.save(); this.router.navigate(['/builder/workouts']); }
We check the validation state of the form using its invalid property and then call the WorkoutBuilderService.save method if the form state is valid.