转换我的文件类型扩展名从我的后端在Angular?



所以我有一个项目,我必须建立一个CMS系统,用户可以上传他们的文件,并可以看到它的详细信息。然而,我从我的数据库得到的数据输出是相当复杂的普通用户,即:图像/png,应用程序/pdf等。从我的老板那里,我不得不把它改成PDF,视频,照片等。

然而,我尝试使用Angular Pipes,但不知道从哪里开始。关于如何通过Angular管道实现这一点,几乎没有文档。谁能帮我把这些数据转换成一些用户友好的术语?

非常感谢!

我代码:

<div class="GuideTable">
<table class="table">
<tr>
<th>Title</th>
<th >Type</th>
<th>Filename</th>
<th>Date</th>
<th>Source</th>
<th>Publication</th>
</tr>
<tr *ngFor="let item of GuidesList$.slice().reverse()">
<th class="notbold">{{item.title}}</th>
<th class="notbold">{{item.type}}</th>
<th class="notbold">{{item.filename}}</th>
<th class="notbold">{{item.date}}</th>
<th class="notbold">{{item.source}}</th>
<th class="notbold">{{item.role}}</th>
</tr>
</table>
</div>

我的TS文件:

ngOnInit(): void {
this.service.getGuidesList().subscribe(response => {
this.GuidesList$=response 
});
}

我非常怀疑缺乏关于管道的信息。但基本上,pipe和其他javascript函数一样,除了每次绑定属性改变时执行(假设它是一个纯管道——它应该是)。

对于一个简单的演示,让我们假设item.type是内容类型MIME Type,我们将其转换为其他可读的内容-PDF, Video字符串等。

这是重命名管道,将item.type作为参数,并基于item.type返回字符串。

import { PipeTransform, Pipe } from '@angular/core';
@Pipe({ name: 'rename' })
export class RenamePipe implements PipeTransform {
transform(typeString: string): string {
if (typeString === 'application/pdf') {
return 'PDF';
} else if (typeString === 'image/png') {
return 'Photo';
} else {
return typeString
}
}
}

Html

<div class="GuideTable">
<table class="table">
<tr>
<th>Title</th>
<th >Type</th>
<th>Filename</th>
<th>Date</th>
<th>Source</th>
<th>Publication</th>
</tr>
<tr *ngFor="let item of items">
<th class="notbold">{{item.title}}</th>
<th class="notbold">{{item.type | rename}}</th>
<th class="notbold">{{item.filename}}</th>
<th class="notbold">{{item.date | date : 'dd-MM-yyyy'}}</th>
<th class="notbold">{{item.source}}</th>
<th class="notbold">{{item.role}}</th>
</tr>
</table>
</div>

你甚至可以使用一些预先构建的管道,如日期管道| date : 'dd-MM-yyyy'

工作示例:https://stackblitz.com/edit/angular-pipes-qhkh8d?file=app%2Frename.pipe.ts


只是一个旁注,在javascript中,我们在camelCase中命名变量GuidesList->guidesList。css类也是一样http://bdavidxyz.com/blog/how-to-name-css-classes/

我们使用$来表示它是一个可观察对象。这是非常不可能的,getGuidesList()返回一个可观察对象(除非你做一些时髦的东西)。请添加getGuidesList(),以便我们也可以看到这部分,并在必要时进行重构。

.slice()似乎不合适,没有必要。

如果你决定手动设置.subscribe(),那么不要忘记设置unsubscribe()

欢迎来到SO。

最新更新