-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathcreate-course.component.ts
113 lines (86 loc) · 3.19 KB
/
create-course.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AngularFirestore} from '@angular/fire/firestore';
import {Course} from '../model/course';
import {catchError, concatMap, last, map, take, tap} from 'rxjs/operators';
import {from, Observable, throwError} from 'rxjs';
import {Router} from '@angular/router';
import {AngularFireStorage} from '@angular/fire/storage';
import firebase from 'firebase/app';
import Timestamp = firebase.firestore.Timestamp;
import {CoursesService} from "../services/courses.service";
@Component({
selector: 'create-course',
templateUrl: 'create-course.component.html',
styleUrls: ['create-course.component.css']
})
export class CreateCourseComponent implements OnInit {
courseId: string;
percentageChanges$: Observable<number>;
iconUrl:string;
form = this.fb.group({
description: ['', Validators.required],
category: ["BEGINNER", Validators.required],
url: [''],
longDescription: ['', Validators.required],
promo: [false],
promoStartAt: [null]
});
constructor(private fb: FormBuilder,
private coursesService: CoursesService,
private afs: AngularFirestore,
private router: Router,
private storage: AngularFireStorage) {
}
uploadThumbnail(event) {
const file: File = event.target.files[0];
console.log(file.name);
const filePath = `courses/${this.courseId}/${file.name}`;
const task = this.storage.upload(filePath, file, {
cacheControl: "max-age=2592000,public"
});
this.percentageChanges$ = task.percentageChanges();
task.snapshotChanges()
.pipe(
last(),
concatMap(() => this.storage.ref(filePath).getDownloadURL()),
tap(url => this.iconUrl = url),
catchError(err => {
console.log(err);
alert("Could not create thumbnail url.");
return throwError(err);
})
)
.subscribe();
}
ngOnInit() {
this.courseId = this.afs.createId();
}
onCreateCourse() {
const val = this.form.value;
const newCourse: Partial<Course> = {
description: val.description,
url: val.url,
longDescription: val.longDescription,
promo: val.promo,
categories: [val.category]
};
newCourse.promoStartAt = Timestamp.fromDate(this.form.value.promoStartAt);
if (this.iconUrl) {
newCourse.iconUrl = this.iconUrl;
}
this.coursesService.createCourse(newCourse, this.courseId)
.pipe(
tap(course => {
console.log("Created new course: ", course);
this.router.navigateByUrl("/courses");
}),
catchError(err => {
console.log(err);
alert("Could not create the course.");
return throwError(err);
})
)
.subscribe();
}
}