0

0

使用 Angular 和 Tailwind CSS 构建 URL 缩短应用程序

PHPz

PHPz

发布时间:2024-07-26 19:46:19

|

634人浏览过

|

来源于dev.to

转载

使用 angular 和 tailwind css 构建 url 缩短应用程序

在本博客中,我们将引导您完成使用 angular 作为前端并使用 tailwind css 进行样式创建 url 缩短器应用程序的过程。 url 缩短器是一个方便的工具,可以将长 url 转换为更短、更易于管理的链接。该项目将帮助您了解如何使用现代 web 开发技术构建功能齐全且美观的 web 应用程序。

先决条件

要学习本教程,您应该对 angular 有基本的了解,并对 tailwind css 有一定的了解。确保您的计算机上安装了 node.js 和 angular cli。

项目设置

1. 创建一个新的 angular 项目

首先,通过在终端中运行以下命令来创建一个新的 angular 项目:

ng new url-shortener-app
cd url-shortener-app

2. 安装 tailwind css

接下来,在您的 angular 项目中设置 tailwind css。通过 npm 安装 tailwind css 及其依赖项:

npm install -d tailwindcss postcss autoprefixer
npx tailwindcss init

通过更新 tailwind.config.js 文件来配置 tailwind css:

module.exports = {
  content: [
    "./src/**/*.{html,ts}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

将 tailwind 指令添加到您的 src/styles.scss 文件中:

@tailwind base;
@tailwind components;
@tailwind utilities;

构建 url 缩短器

3. 创建 url 模型

创建 url 模型来定义 url 数据的结构。添加新文件 src/app/models/url.model.ts:

export type urls = url[];

export interface url {
  _id: string;
  originalurl: string;
  shorturl: string;
  clicks: number;
  expirationdate: string;
  createdat: string;
  __v: number;
}

4. 设置 url 服务

创建一个服务来处理与 url 缩短相关的 api 调用。添加新文件 src/app/services/url.service.ts:

杰易CRM客户关系管理系统
杰易CRM客户关系管理系统

软件介绍 a.. 当今的市场压力迫使企业在提高产品质量和性能的同时,降低成本和缩短产品上市的时间。每个企业都在努力更新自己,包括其生产过程和产品,以满足这些需求。实现这些目标的三种方法是:业务处理再设计、新技术应用、与顾客形成战略联盟。 b.. 对所有的商业应用只有建立整体的IT体系结构,才能形成战略优势,才能确定企业的突破口。这种新的体系结构是以三层结构标准为基础的客户关系

下载
import { httpclient } from '@angular/common/http';
import { injectable } from '@angular/core';
import { observable } from 'rxjs';
import { url, urls } from '../models/url.model';
import { environment } from '../../environments/environment';

@injectable({
  providedin: 'root',
})
export class urlservice {
  private apiurl = environment.apiurl;

  constructor(private http: httpclient) {}

  shortenurl(originalurl: string): observable {
    return this.http.post(`${this.apiurl}/shorten`, { originalurl });
  }

  getallurls(): observable {
    return this.http.get(`${this.apiurl}/urls`);
  }

  getdetails(id: string): observable {
    return this.http.get(`${this.apiurl}/details/${id}`);
  }

  deleteurl(id: string): observable {
    return this.http.delete(`${this.apiurl}/delete/${id}`);
  }
}

5. 创建缩短 url 组件

生成一个用于缩短 url 的新组件:

ng generate component shorten

更新组件的 html (src/app/shorten/shorten.component.html) 如下所示:

url shortener

@if (urlform.get('originalurl')?.invalid && (urlform.get('originalurl')?.dirty || urlform.get('originalurl')?.touched)) { }
@if (errormsg) {

{{ errormsg }}

} @if (shorturl) {

shortened url: {{ shorturl }} @if (copymessage) { {{ copymessage }} }

}

all urls

@if (isloading) {
loading...
} @else if (error) {

{{ error }}

} @else { @if (urls.length > 0 && !isloading && !error) {
    @for (url of urls; track $index) {
  • }
} @else {
no urls found.
} }
@if (showdeletemodal) {

confirm deletion

are you sure you want to delete this url?

} @if (showdetailsmodal) {

url details

@if (isloading) {

loading...

} @else {

short url: {{ selectedurl.shorturl }}

original url: {{ selectedurl.originalurl }}

clicks: {{ selectedurl.clicks }}

created at: {{ selectedurl.createdat | date: 'medium' }}

expires at: {{ selectedurl.expirationdate | date: 'medium' }}

}
}

6. 向组件添加逻辑

更新组件的 typescript 文件(src/app/shorten/shorten.component.ts)以处理表单提交和 api 交互:

import { component, inject, oninit } from '@angular/core';
import { urlservice } from '../services/url.service';
import {
  formcontrol,
  formgroup,
  reactiveformsmodule,
  validators,
} from '@angular/forms';
import { url } from '../models/url.model';
import { environment } from '../../environments/environment';
import { datepipe } from '@angular/common';
import { subject, takeuntil } from 'rxjs';

@component({
  selector: 'app-shorten',
  standalone: true,
  imports: [datepipe, reactiveformsmodule],
  templateurl: './shorten.component.html',
  styleurl: './shorten.component.scss',
})
export class shortencomponent implements oninit {
  shorturl: string = '';
  redirecturl = environment.apiurl + '/';
  copymessage: string = '';
  copylistmessage: string = '';
  urls: url[] = [];
  showdeletemodal = false;
  showdetailsmodal = false;
  urltodelete = '';
  copyindex: number = -1;
  selectedurl: url = {} as url;
  isloading = false;
  isloading = false;
  error: string = '';
  errormsg: string = '';
  urlform: formgroup = new formgroup({});
  private unsubscribe$: subject = new subject();

  urlservice = inject(urlservice);

  ngoninit() {
    this.urlform = new formgroup({
      originalurl: new formcontrol('', [
        validators.required,
        validators.pattern('^(http|https)://.*$'),
      ]),
    });
    this.getallurls();
  }

  shortenurl() {
    if (this.urlform.valid) {
      this.urlservice.shortenurl(this.urlform.value.originalurl).pipe(takeuntil(this.unsubscribe$)).subscribe({
        next: (response) => {
          // console.log('shortened url: ', response);
          this.shorturl = response.shorturl;
          this.getallurls();
        },
        error: (error) => {
          console.error('error shortening url: ', error);
          this.errormsg = error?.error?.message || 'an error occurred!';
        },
      });
    }
  }

  getallurls() {
    this.isloading = true;
    this.urlservice.getallurls().pipe(takeuntil(this.unsubscribe$)).subscribe({
      next: (response) => {
        // console.log('all urls: ', response);
        this.urls = response;
        this.isloading = false;
      },
      error: (error) => {
        console.error('error getting all urls: ', error);
        this.isloading = false;
        this.error = error?.error?.message || 'an error occurred!';
      },
    });
  }

  showdetails(id: string) {
    this.showdetailsmodal = true;
    this.getdetails(id);
  }

  getdetails(id: string) {
    this.isloading = true;
    this.urlservice.getdetails(id).subscribe({
      next: (response) => {
        // console.log('url details: ', response);
        this.selectedurl = response;
        this.isloading = false;
      },
      error: (error) => {
        console.error('error getting url details: ', error);
        this.error = error?.error?.message || 'an error occurred!';
      },
    });
  }

  copyurl(url: string) {
    navigator.clipboard
      .writetext(url)
      .then(() => {
        // optional: display a message or perform an action after successful copy
        console.log('url copied to clipboard!');
        this.copymessage = 'copied!';
        settimeout(() => {
          this.copymessage = '';
        }, 2000);
      })
      .catch((err) => {
        console.error('failed to copy url: ', err);
        this.copymessage = 'failed to copy url';
      });
  }

  copylisturl(url: string, index: number) {
    navigator.clipboard
      .writetext(url)
      .then(() => {
        // optional: display a message or perform an action after successful copy
        console.log('url copied to clipboard!');
        this.copylistmessage = 'copied!';
        this.copyindex = index;
        settimeout(() => {
          this.copylistmessage = '';
          this.copyindex = -1;
        }, 2000);
      })
      .catch((err) => {
        console.error('failed to copy url: ', err);
        this.copylistmessage = 'failed to copy url';
      });
  }

  preparedelete(url: string) {
    this.urltodelete = url;
    this.showdeletemodal = true;
  }

  confirmdelete() {
    // close the modal
    this.showdeletemodal = false;
    // delete the url
    this.deleteurl(this.urltodelete);
  }

  deleteurl(id: string) {
    this.urlservice.deleteurl(id).subscribe({
      next: (response) => {
        // console.log('deleted url: ', response);
        this.getallurls();
      },
      error: (error) => {
        console.error('error deleting url: ', error);
        this.error = error?.error?.message || 'an error occurred!';
      },
    });
  }

  ngondestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}

7.更新应用程序组件的html文件(src/app/app.component.html)


8.更新应用程序配置文件(src/app/app.config.ts)

import { applicationconfig, providezonechangedetection } from '@angular/core';
import { providerouter } from '@angular/router';

import { routes } from './app.routes';
import { providehttpclient } from '@angular/common/http';

export const appconfig: applicationconfig = {
  providers: [
    providezonechangedetection({ eventcoalescing: true }),
    providerouter(routes),
    providehttpclient(),
  ],
};

9.更新应用程序路由文件(src/app/app.routes.ts)

import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: '',
    loadComponent: () =>
      import('./shorten/shorten.component').then((m) => m.ShortenComponent),
  },
];

结论

您已经使用 angular 和 tailwind css 成功构建了 url 缩短器应用程序。该项目演示了如何集成现代前端技术来创建功能强大且时尚的 web 应用程序。借助 angular 的强大功能和 tailwind css 实用程序优先的方法,您可以轻松构建响应灵敏且高效的 web 应用程序。

请随意通过添加用户身份验证等功能来扩展此应用程序。祝您编码愉快!

立即学习前端免费学习笔记(深入)”;

探索代码

访问 github 存储库以详细探索代码。


相关专题

更多
css
css

css是层叠样式表,用来表现HTML或XML等文件样式的计算机语言,不仅可以静态地修饰网页,还可以配合各种脚本语言动态地对网页各元素进行格式化。php中文网还为大家带来html的相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

524

2023.06.15

css居中
css居中

css居中:1、通过“margin: 0 auto; text-align: center”实现水平居中;2、通过“display:flex”实现水平居中;3、通过“display:table-cell”和“margin-left”实现居中。本专题为大家提供css居中的相关的文章、下载、课程内容,供大家免费下载体验。

262

2023.07.27

css如何插入图片
css如何插入图片

cssCSS是层叠样式表(Cascading Style Sheets)的缩写。它是一种用于描述网页或应用程序外观和样式的标记语言。CSS可以控制网页的字体、颜色、布局、大小、背景、边框等方面,使得网页的外观更加美观和易于阅读。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

753

2023.07.28

css超出显示...
css超出显示...

在CSS中,当文本内容超出容器的宽度或高度时,可以使用省略号来表示被隐藏的文本内容。本专题为大家提供css超出显示...的相关文章,相关教程,供大家免费体验。

539

2023.08.01

css字体颜色
css字体颜色

CSS中,字体颜色可以通过属性color来设置,用于控制文本的前景色,字体颜色在网页设计中起到很重要的作用,具有以下表现作用:1、提升可读性;2、强调重点信息;3、营造氛围和美感;4、用于呈现品牌标识或与品牌形象相符的风格。

759

2023.08.10

什么是css
什么是css

CSS是层叠样式表(Cascading Style Sheets)的缩写,是一种用于描述网页(或其他基于 XML 的文档)样式与布局的标记语言,CSS的作用和意义如下:1、分离样式和内容;2、页面加载速度优化;3、实现响应式设计;4、确保整个网站的风格和样式保持统一。

604

2023.08.10

css三角形怎么写
css三角形怎么写

CSS可以通过多种方式实现三角形形状,本专题为大家提供css三角形怎么写的相关教程,大家可以免费体验。

560

2023.08.21

css设置文字颜色
css设置文字颜色

CSS(层叠样式表)可以用于设置文字颜色,这样做有以下好处和优势:1、增加网页的可视化效果;2、突出显示某些重要的信息或关键字;3、增强品牌识别度;4、提高网页的可访问性;5、引起不同的情感共鸣。

392

2023.08.22

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

9

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.8万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 2.9万人学习

CSS教程
CSS教程

共754课时 | 19.5万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号