· 6 years ago · Apr 01, 2020, 05:34 PM
1//this is the media service, it connects both the advice and media component
2//when you create a new advice, you get the newly created advice id from the server, pass it to the media service, and navigate to the media component, which loads the rest of the data into the media service and tells it to make the request
3
4export class MediaService {
5 request: MediaReq = new MediaReq();
6
7 constructor(private api: ApiService) {}
8
9 setRequest(advice_id, isNew) {
10 this.request.advice_id = advice_id.msg;
11 this.request.isNew = isNew;
12 }
13
14 upload(form: FormGroup) {
15 if (this.request.isNew) {
16 form.get("advice_id").setValue(this.request.advice_id);
17 console.log(form)
18 this.api.uploadMedia(toFormData(form))
19 .subscribe(result => console.log(result))
20 } else {
21 this.api.patchMedia(toFormData(form), this.request.advice_id);
22 }
23 }
24}
25
26function toFormData(form: FormGroup) {
27 let formData = new FormData()
28 for (var key in form.value) {
29 formData.append(key, form.value[key])
30 }
31 return formData;
32}
33
34
35
36// this is in the advice component
37 createAdvice() {
38 if (!Array.isArray(this.advice["phones"]))
39 this.advice["phones"] = this.advice["phones"]
40 .replace(/\s/g, "")
41 .split(",");
42
43 this.api.createAdvice(this.advice).subscribe({
44 next: id => {
45 this.media.setRequest(id, true);
46 this.router.navigate(["/upload"]);
47 console.log(id);
48 }
49 });
50 }
51}
52
53
54
55
56
57//this happens in the Media Component
58
59ngOnInit() {
60 this.uploadForm = this.formBuilder.group({
61 image: new FormControl(),
62 name: new FormControl(),
63 type: new FormControl(),
64 advice_id: new FormControl()
65 });
66 }
67
68 onFileSelect(event) {
69 if (event.target.files.length > 0) {
70 const file = event.target.files[0];
71 this.uploadForm.get("image").setValue(file);
72 this.uploadForm.get("name").setValue(file.name);
73 }
74 }
75
76 onSubmit() {
77 this.media.upload(this.uploadForm)
78 }