Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ------------------------Artist Form Component.ts-----------------------------
- import { Component, OnInit } from '@angular/core';
- import { ArtistsService } from './../../services/artists.service';
- import { Artist } from './../../models/artist.model';
- import { FormBuilder, FormGroup, Validators } from '@angular/forms';
- import { Router } from '@angular/router';
- import { AuthService } from 'src/app/services/auth.service';
- import * as firebase from 'firebase/app';
- import 'firebase/app';
- import 'firebase/firestore';
- import 'firebase/auth';
- import 'firebase/database';
- import 'firebase/storage';
- @Component({
- selector: 'app-artist-form',
- templateUrl: './artist-form.component.html',
- styleUrls: ['./artist-form.component.scss']
- })
- export class ArtistFormComponent implements OnInit {
- artistForm: FormGroup;
- fileIsUploading = false;
- fileUrl: string;
- fileUploaded = false;
- errorMessage: string;
- constructor(private formBuilder: FormBuilder,
- private artistsService: ArtistsService,
- private router: Router,
- private authService: AuthService) { }
- ngOnInit() {
- this.initForm();
- }
- initForm() {
- this.artistForm = this.formBuilder.group({
- nickname: ['', Validators.required],
- email: ['', [Validators.required, Validators.email]],
- password: ['', [Validators.required, Validators.pattern(/[0-9a-zA-Z]{6,}/)]],
- patreon: ['', [Validators.required, Validators.pattern('https://www.patreon.com/[0-9a-zA-Z]{6,}')]],
- roles: ['', Validators.required],
- country: ['', Validators.required],
- photo: ['', Validators.required],
- description: ['', Validators.required]
- });
- }
- onSaveArtist() {
- const nickname = this.artistForm.get('nickname').value;
- const email = this.artistForm.get('email').value;
- const password = this.artistForm.get('password').value;
- const patreon = this.artistForm.get('patreon').value;
- const roles = this.artistForm.get('roles').value;
- const country = this.artistForm.get('country').value;
- const description = this.artistForm.get('description').value;
- const arrayPath = this.artistForm.get('photo').value.split("\\"); // arrayPath[2] is our photo's name ;) I figured this out by
- //displaying arrayPath, you can try that out to be convinced! ;)
- var photo = 'empty';
- const storageRef = firebase.storage().ref();
- const photoRef = storageRef.child('/uploads/' + arrayPath[2]);
- photoRef.getDownloadURL().then( (url) => {
- photo = url.toString();
- this.authService.createNewUser(email, password).then(
- () => {
- var newArtist = new Artist(nickname, email, password, patreon, roles, 'offline', country, photo, description);
- this.artistsService.createNewArtist(newArtist);
- this.router.navigate(['/artists']);
- },
- (error) => {
- this.errorMessage = error;
- }
- );
- }).catch(function (error) {
- // Handle any errors
- console.log("error in getting download url.." + error);
- });
- }
- onUploadFile(file: File) {
- this.fileIsUploading = true;
- this.artistsService.uploadFile(file).then(
- (url: string) => {
- this.fileUrl = url;
- this.fileIsUploading = false;
- this.fileUploaded = true;
- }
- );
- }
- detectFiles(event) {
- this.onUploadFile(event.target.files[0]);
- }
- }
- ---------------------------------Artists Service---------------------------
- import * as firebase from 'firebase/app';
- import 'firebase/app';
- import 'firebase/firestore';
- import 'firebase/auth';
- import 'firebase/database';
- import 'firebase/storage';
- import { Artist } from '../models/artist.model';
- import { Injectable } from '@angular/core';
- import { Subject } from 'rxjs/Subject';
- import { DataSnapshot } from '@angular/fire/database/interfaces';
- @Injectable()
- export class ArtistsService {
- constructor() {
- this.getArtists();
- }
- artists: Artist[] = [];
- artistsSubject = new Subject<Artist[]>();
- artistsFiltered: Artist[] = [];
- ids: string[] = [];
- progress: number;
- emitArtists() {
- this.artistsSubject.next(this.artists);
- }
- saveArtists() {
- firebase.database().ref('/artists').set(this.artists);
- }
- getArtists() {
- firebase.database().ref('/artists')
- .on('value', (data: DataSnapshot) => {
- this.ids = [];
- this.artists = data.val() ? data.val() : [];
- this.emitArtists();
- this.artists.forEach((artist, index) => {
- this.ids.push(index.toString());
- });
- }
- );
- }
- getFilteredArtists(filter: string) { // works perfectly
- if(filter)
- {
- this.artistsFiltered = []; // we need to initialize this or we'll always get the previous filtered artists..
- this.ids = [];
- for(var i=0; i < this.artists.length; i++ )
- {
- if(this.artists[i]['nickname'].includes(filter) || this.artists[i]['roles'].indexOf(filter) != -1) // if the artist's nickname includes filter or if filter is one of his roles
- {
- this.artistsFiltered.push(this.artists[i]); // we add him
- this.ids.push(i.toString()); // we add the id so that we keep onViewArtist(id) working correctly
- }
- }
- this.artists = this.artistsFiltered; // we set our new artists array
- this.emitArtists();
- }
- }
- getSingleArtist(id: number) {
- return new Promise(
- (resolve, reject) => {
- firebase.database().ref('/artists/' + id).once('value').then(
- (data: DataSnapshot) => {
- resolve(data.val());
- }, (error) => {
- reject(error);
- }
- );
- }
- );
- }
- createNewArtist(newArtist: Artist) {
- this.artists.push(newArtist);
- this.saveArtists();
- //firebase.database().ref('/artists').push(newArtist);
- this.emitArtists();
- }
- removeArtist(artist: Artist) {
- if(artist.photo) {
- const storageRef = firebase.storage().refFromURL(artist.photo);
- storageRef.delete().then(
- () => {
- console.log('Photo removed!');
- },
- (error) => {
- console.log('Could not remove photo! : ' + error);
- }
- );
- }
- const artistIndexToRemove = this.artists.findIndex(
- (artistEl) => {
- if(artistEl === artist) {
- return true;
- }
- }
- );
- this.artists.splice(artistIndexToRemove, 1);
- this.saveArtists();
- this.emitArtists();
- }
- uploadFile(file: File) {
- return new Promise(
- (resolve, reject) => {
- const upload = firebase.storage().ref().child('uploads/' + file.name).put(file);
- upload.on(firebase.storage.TaskEvent.STATE_CHANGED,
- (snapshot) => {
- console.log((upload.snapshot.bytesTransferred / upload.snapshot.totalBytes) * 100);
- this.progress = (upload.snapshot.bytesTransferred / upload.snapshot.totalBytes) * 100;
- },
- (error) => {
- console.log('Erreur de chargement ! : ' + error);
- reject();
- },
- () => {
- resolve(upload.snapshot.downloadURL);
- }
- );
- }
- );
- }
- }
- ---------------------------- Follow Service --------------------------
- import { Injectable } from '@angular/core';
- import { AngularFireDatabase } from 'angularfire2/database';
- import { Subject } from 'rxjs/Subject';
- import { DataSnapshot } from '@angular/fire/database/interfaces';
- import * as firebase from 'firebase/app';
- import 'firebase/app';
- import 'firebase/firestore';
- import 'firebase/auth';
- import 'firebase/database';
- import 'firebase/storage';
- @Injectable()
- export class FollowService {
- constructor() { }
- followers: string[] = []; // in before User[]
- nbFollowers: number;
- followersSubject = new Subject<string[]>(); // in before Subject<User[]>
- following: string[] = []; // in before Artist[]
- followingSubject = new Subject<string[]>(); // in before Subject<Artist[]>
- indexFollower: number;
- indexFollowing: number;
- emitFollowers() {
- this.followersSubject.next(this.followers);
- }
- emitFollowing() {
- this.followingSubject.next(this.following);
- }
- saveFollowers(artistId) {
- firebase.database().ref('/artists/' + artistId + '/followers').set(this.followers);
- }
- saveFollowing(userId) {
- firebase.database().ref('/users/' + userId + '/following').set(this.following);
- }
- getFollowers(artistId) {
- firebase.database().ref('/artists/' + artistId + '/followers')
- .on('value', (data: DataSnapshot) => {
- this.followers = data.val() ? data.val() : [];
- this.nbFollowers = this.followers.length;
- this.emitFollowers();
- }
- );
- }
- getFollowing(userId) {
- firebase.database().ref('/users/' + userId + '/following')
- .on('value', (data: DataSnapshot) => {
- this.following = data.val() ? data.val() : [];
- this.emitFollowing();
- }
- );
- }
- // TO DO: need to find a better way to add only the new people involved in this follow action and not the whole array every time we call it .. smth similar to the addNewUser
- createNewFollower(newFollower: string, newFollowing: string) {
- this.getFollowers(newFollowing); // on obtient la liste des followers de cet artiste ayant artistId comme Id
- this.followers.push(newFollower); // on ajoute le nouveau follower dans le tableau local des followers
- this.saveFollowers(newFollowing); // on le monte ce tableau des followers dans firebase
- this.emitFollowers(); // sans cette fonction, le changement réel ne va pas avoir lieu, j'ai testé sans cette ligne pour voir la difference!
- this.getFollowing(newFollower); // on obtient la liste des following de ce user ayant userId comme Id
- this.following.push(newFollowing); // on ajoute le nouveau artiste dans le tableau local des following
- this.saveFollowing(newFollower); // on monte ce tableau des following dans firebase
- this.emitFollowing(); // sans cette fonction, le changement réel ne va pas avoir lieu, j'ai testé sans cette ligne pour voir la difference!
- }
- // concernant la suppression, il y'a un prob c'est que si on veut supprimer quelqu'un , ce quelqu'un a evidemment changé de structure, car ces followers/following ne sont plus les mêmes, donc on doit dès le départ les inserer avec des tableau follower/following vides.
- deleteFollower(follower: string)
- {
- console.log(this.followers);
- this.indexFollower = this.followers.indexOf(follower);
- console.log("indexFollower = " + this.indexFollower);
- if(this.indexFollower !== -1)
- {
- this.followers.splice(this.indexFollower, 1);
- }
- }
- deleteFollowing(following: string)
- {
- console.log(this.following);
- this.indexFollowing = this.following.indexOf(following);
- console.log("indexFollowing = " + this.indexFollowing);
- console.log(following);
- if(this.indexFollowing !== -1)
- {
- this.following.splice(this.indexFollowing, 1);
- }
- }
- // prob is : when I try to remove the follower & the following I just can't since in firebase their attributes are not put in the right order --> I created 2 new models for that
- removeFollower(follower: string, following: string) {
- this.getFollowers(following); // on obtient la liste des followers de cet artiste ayant artistId comme Id
- this.deleteFollower(follower); // on supprime ce user du tableau des followers
- this.saveFollowers(following); // on monte ce tableau des followers dans firebase
- this.emitFollowers();
- this.getFollowing(follower); // on obtient la liste des following de ce user ayant userId comme Id
- this.deleteFollowing(following); // on supprime cet artiste du tableau des following
- this.saveFollowing(follower); // on monte ce tableau des following dans firebase
- this.emitFollowing();
- }
- }
- -------------Single Artist Component.ts-------------------------
- import { Component, OnInit, Input, Query } from '@angular/core';
- import { ArtistsService } from './../../services/artists.service';
- import { Artist } from './../../models/artist.model';
- import { ActivatedRoute, Router } from '@angular/router';
- import { FollowService } from 'src/app/services/follow.service';
- import { User } from 'src/app/models/user.model';
- import { UsersService } from 'src/app/services/users.service';
- import * as firebase from 'firebase/app';
- import 'firebase/auth';
- @Component({
- selector: 'app-single-artist',
- templateUrl: './single-artist.component.html',
- styleUrls: ['./single-artist.component.scss']
- })
- export class SingleArtistComponent implements OnInit {
- artist: Artist;
- mailLink: string;
- currentArtistId;
- currentUserId: string;
- user: User;
- isFollowing: boolean;
- nbFollowers: number;
- makeItCleaner = 'follower';
- constructor(private route: ActivatedRoute,
- private artistsService: ArtistsService,
- private router: Router,
- private followService: FollowService,
- private usersService: UsersService) { }
- ngOnInit() {
- this.artist = new Artist('', '', '', '', [], '', '','', '');
- this.currentArtistId = this.route.snapshot.params['id']; // get the Id of the artist that I'm looking at
- this.currentUserId = firebase.auth().currentUser.uid; // get the Id of the current user, we still don't know if he's a user or an artist
- console.log(this.currentUserId); // for testing
- // need to get the artist the current user is looking at ;)
- this.artistsService.getSingleArtist(this.currentArtistId).then(
- (artist: Artist) => {
- this.artist = artist;
- this.mailLink = 'http://' + this.artist.email + '/';
- console.log(this.artist);
- this.followService.getFollowers(this.currentArtistId); // so that we set the variable nbfollowers in the follow service ;)
- this.nbFollowers = this.followService.nbFollowers;
- if(this.nbFollowers > 1) this.makeItCleaner += 's';
- }
- );
- // then I need to get the current user, the current user and the artist will help me in displaying whether the follow or unfollow button ;)
- this.usersService.getSingleUser(this.currentUserId).then( // this section is important to determine if the uid we have is really a user's uid
- (user: User) => {
- this.user = user;
- if(this.user)
- {
- this.followService.getFollowing(this.currentUserId); // so that we set the variable following of the current user to have all the artists he's following
- this.isFollowing = this.followService.following.some((item) => item == this.currentArtistId); // so that I know if this user is already following the artist or not.. I'll use it to know which button should I display: Follow or Unfollow btn
- console.log(this.isFollowing);
- }
- else console.log("this is not a user!");
- }
- );
- }
- onBack() { // working perfectly
- this.artistsService.getArtists(); // without this line, if we hit return and go to artists page, we'll only find the previous artists so this helps to find all the artists again
- this.router.navigate(['/artists']);
- }
- onFollow() {
- console.log(this.user); // for testing
- this.followService.createNewFollower(this.currentUserId, this.currentArtistId);
- this.isFollowing = this.followService.following.some((item) => item == this.currentArtistId);
- // just to make it look more realistic: if the followers were 1 and became 2 for exple ==> we should display 2 followers instead of 2 follower ;)
- this.nbFollowers = this.followService.nbFollowers;
- if(this.nbFollowers > 1) this.makeItCleaner = 'followers';
- }
- onUnfollow() {
- console.log(this.user); // for testing
- this.followService.removeFollower(this.currentUserId, this.currentArtistId);
- this.isFollowing = this.followService.following.some((item) => item == this.currentArtistId);
- // just to make it look more realistic: if the followers were 2 and became one for exple ==> we should display 1 follower instead of 1 followers ;)
- this.nbFollowers = this.followService.nbFollowers;
- if(this.nbFollowers < 2) this.makeItCleaner = 'follower';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement