Files
itzmineydev/src/app/shared/shortener/shortener.component.ts
T

131 lines
2.9 KiB
TypeScript

import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import {ShortenerService} from '../services/shortener.service';
import {FormsModule} from '@angular/forms';
import { SlicePipe } from '@angular/common';
import {AuthService} from '../services/auth.service';
@Component({
selector: 'app-shortener',
imports: [
FormsModule,
SlicePipe
],
templateUrl: './shortener.component.html',
styleUrl: './shortener.component.css'
})
export class ShortenerComponent implements OnInit {
@Input() isOpen: boolean = false;
@Output() onClose = new EventEmitter<void>();
urls: any[] = [];
noURLs: boolean = false;
og_url: string = '';
short_name: string | null = null;
deleteId: number | null = null;
copiedShort: string | null = null;
constructor(
private shortenerService: ShortenerService,
private authService: AuthService,
) {}
ngOnInit() {
this.loadURLs();
}
loadURLs(): void {
const token = this.authService.token;
if (!token) {
return;
}
this.shortenerService.getAllURLs(token).subscribe({
next: (data) => {
this.urls = data;
this.noURLs = data.length === 0;
},
error: (err) => {
console.error('Error loading URLs:', err)
}
});
}
createShortURL(form: any) {
const og_url = form.value.og_url;
const short_name = form.value.short_name ?? null;
if (!og_url) {
alert('Original URL Required!');
return;
}
const token = this.authService.token;
if (!token) {
return;
}
const req$ = short_name
? this.shortenerService.postURL(token, og_url, short_name)
: this.shortenerService.postURL(token, og_url);
req$.subscribe({
next: () => {
alert('Short URL created successfully!');
this.loadURLs();
},
error: (error) => {
alert('Error creating Short URL');
console.error(error);
}
});
}
deleteShortURL(form: any) {
const id = form.value.deleteId;
if (!id || isNaN(Number(id))) {
alert('Invalid input. Please enter a valid Short URL ID.');
return;
}
const token = this.authService.token!;
if (!token) {
return;
}
this.shortenerService.deleteURL(Number(id), token).subscribe({
next: () => {
alert(`Short URL with ID ${id} deleted successfully`);
this.loadURLs();
},
error: (error) => {
alert(`Error deleting Short URL ${id}: ${error.message}`);
console.error('Error deleting Short URL:', error);
}
});
}
copyShortUrl(shortCode: string): void {
const shortUrl = `https://itz.sh/${shortCode}`;
navigator.clipboard.writeText(shortUrl).then(() => {
this.copiedShort = shortCode;
setTimeout(() => {
if (this.copiedShort === shortCode) this.copiedShort = null;
}, 2000);
}).catch(() => {
});
}
closeShortenerModal() {
this.isOpen = false;
this.onClose.emit();
}
}