Saving localstorage draft to database
unknown
typescript
2 years ago
2.1 kB
33
Indexable
// Single Step
export class DefinitionComponent implements OnInit {
definitionForm!: FormGroup;
constructor(
private fb: FormBuilder,
private draftS: DraftService,
) {}
ngOnInit():void {
// Form setup
this.definitionForm = this.fb.group({
marketing_name: ['', Validators.required],
technical_name: ['', Validators.required],
description: ['', Validators.required],
portal: ['', Validators.required],
type: ['', Validators.required],
start_date: ['', Validators.required],
finish_date: ['', Validators.required],
});
// Fill out form fields (on init) with data from localstorage
this.fillForm(StepsEnum.Definition);
// Listen to Form Value Changes to set new Values inside the form
this.definitionForm.valueChanges.subscribe(value => {
this.draftS.saveDraft(StepsEnum.Definition, value);
});
}
// Fill out form fields with data from localstorage
fillForm(stepName:string) {
const localStorageData = this.draftS.getLocalStorageData(stepName);
// check if data from localstorage exists
if (localStorageData !== null) {
// if data does exist, use that data to setValue on the form
this.definitionForm.setValue(JSON.parse(localStorageData));
}
}
}
// Draft Service
export class DraftService {
constructor() { }
// Save Draft
saveDraft(stepName:string, value:JSON) {
localStorage.setItem(stepName, JSON.stringify(value));
}
// Get Data from the localstorage
getLocalStorageData(stepName:string) {
return localStorage.getItem(stepName);
}
}
// Create promotion service
export class CreatePromotionService {
stepsEnum = StepsEnum;
// This is the firebase URL -> https://promotions-58746-default-rtdb.firebaseio.com/
create(draft:DraftService) {
// 1. loop through each localstorage draft
var keys = Object.keys(this.stepsEnum);
keys.forEach((obj, index) => {
// 2. if given key is not empty save to database
// 3. if saved then clear the draft
// 4. redirect
});
}
}
Editor is loading...