一、管道使用场景
每个应用开始的时候差不多都是一些简单任务:获取数据、转换它们,然后把它们显示给用户。通过引入Angular管道,我们可以把这种简单的“显示-值”转换器声明在HTML中。
二、内置管道
Angular内置了一些管道,比如DatePipe、UpperCasePipe、LowerCasePipe、CurrencyPipe和PercentPipe。 它们全都可以直接用在任何模板中。
比如在如下代码中使用:
import { Component } from '@angular/core';
@Component({
selector: 'hero-birthday',
template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
<p>The hero's birthday is {{ birthday | date }}</p>
当然我们也可以传递参数到管道中:
<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>
这样我们便可以格式化我们的时间为指定的格式。
我们可以把管道链在一起,以组合出一些潜在的有用功能。
The chained hero's birthday is
{{ birthday | date | uppercase}}
三、自定义管道
在ioinic2的项目中我们可以使用命令
ionic g pipe myPipe
便可自动生成如下代码:
@Pipe({
name: 'myPipe',
})
export class MyPipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: string, ...args) {
return value.toLowerCase();
}
}
只要我们修改transform方法遍可自定义我们的管道,比如:
transform(str: string, ...args) {
if (!str) return ''
var date = new Date(str)
var time = new Date().getTime() - date.getTime() // 现在的时间-传入的时间 = 相差的时间(单位 = 毫秒)
if (time < 0) {
return ''
} else if ((time / 1000 < 30)) {
return '刚刚'
} else if (time / 1000 < 60) {
return parseInt((time / 1000)+'') + '秒前'
} else if ((time / 60000) < 60) {
return parseInt((time / 60000)+'') + '分钟前'
} else if ((time / 3600000) < 24) {
return parseInt(time / 3600000+'') + '小时前'
} else if ((time / 86400000) < 31) {
return parseInt(time / 86400000+'') + '天前'
} else if ((time / 2592000000) < 12) {
return parseInt(time / 2592000000+'') + '月前'
} else {
return parseInt(time / 31536000000+'') + '年前'
}
}
在我们的ionic模块中只要
//xxx.module.ts
import { NgModule } from '@angular/core'
import { IonicPageModule } from 'ionic-angular'
import { AllRequestPage } from './all-request'
import { MyPipe} from '../../pipes/my/my'
@NgModule({
declarations: [AllRequestPage, MyPipe],
imports: [IonicPageModule.forChild(AllRequestPage)],
exports: [AllRequestPage]
})
export class AllRequestPageModule { }
////xxx.html
<ion-content style='background:#DADADA'>
<div class='container'>
<div class="content" *ngFor='let item of items'>
<div class="top-div">
<div class='img' [style.background]="'url(' +item.author.avatar_url+ ')'"></div>
<div class="box">
<label>{{item.author.loginname}}</label>
<div>
<time>{{item.create_at | myPipe}}</time>
<span>#分享</span>
</div>
</div>
</div>
<div class="title-div">
<strong>{{ item.title }}</strong>
</div>
<div class="foot-div">
<div class="item click">
<ion-icon name="eye-outline"></ion-icon>
<span>{{ item.visit_count > 0 ? item.visit_count : '暂无阅读' }}</span>
</div>
<div class="item reply">
<ion-icon name="text-outline"></ion-icon>
<span>{{ item.reply_count > 0 ? item.reply_count : '暂无评论' }}</span>
</div>
<div class="item">
<span>{{ item.last_reply_at | myPipe}}</span>
</div>
</div>
</div>
</div>
</ion-content>
这样便完成了自定义管道的使用。