use*_*246 5 angular2-pipe angular
我按照这个链接创建了我自己的时间前管道: Angular 2 "time ago" pipe
但是当我注入并使用它时,我看到了错误:
模板解析错误:找不到管道“timeAgo”
下面是我的代码,请帮我解决这个问题,非常感谢!!
timeAgo.pipe.ts
import { Pipe, ChangeDetectorRef } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/startWith';
@Pipe({
name: 'timeAgo',
pure: false
})
export class TimeAgoPipe extends AsyncPipe {
value: Date;
timer: Observable<string>;
constructor(private ref: ChangeDetectorRef){
super(ref);
}
transform(obj: any, args?: any[]): any {
if(obj instanceof Date) {
this.value = obj;
if(!this.timer) {
this.timer = this.getObservable();
}
return this.timer;
}
return this.transform(obj, args);
}
private getObservable(){
const INTERVAL = 1000 * 45;
const ONE_MINUTE = 60;
const ONE_HOUR = 60 * 60;
const ONE_DAY = 60 * 60 * 24;
const ONE_MONTH = 60 * 60 * 24 * 30;
const ONE_YEAR = 60 * 60 * 24 * 30 * 12;
return Observable.interval(INTERVAL).startWith(0).map(() => {
// current time
let now = Date.now();
// time since message was sent in seconds
let delta = (now - this.value.getTime()) / 1000;
// format string
if(delta < ONE_MINUTE) {
return 'just now';
}
if(delta < ONE_HOUR) {
return Math.floor(delta / ONE_MINUTE) + 'min(s) ago';
}
if(delta < ONE_DAY) {
return Math.floor(delta / ONE_HOUR) + 'hour(s) ago';
}
if(delta < ONE_MONTH) {
return Math.floor(delta / ONE_DAY) + 'day(s) ago';
}
if(delta < ONE_YEAR) {
return Math.floor(delta / ONE_MONTH) + 'month ago';
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
主文件
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode, provide, PLATFORM_PIPES } from '@angular/core';
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
provide(PLATFORM_PIPES, {
useValue: [TimeAgoPipe],
multi: true
})
]);
Run Code Online (Sandbox Code Playgroud)
post.component.html
<ul *ngIf="posts">
<li *ngFor="let post of posts">
{{ post.created_at | timeAgo}}
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
似乎已PLATFORM_PIPES被弃用(https://github.com/angular/angular/blob/master/CHANGELOG.md)。
您可以使用本文提供的方法来设置全局管道:https://medium.com/@jecelynyeen/angular2-platform-pipes-globally-available-custom-pipe-will-be-deprecated-soon-c6ad16812c11#。 ntmim1t9x
bootstrap(AppComponent, [
provide(CompilerConfig, {
useValue: new CompilerConfig({
platformPipes: [...COMMON_PIPES, TimeAgoPipe],
platformDirectives: [...COMMON_DIRECTIVES],
genDebugInfo: true
})
}),
]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4764 次 |
| 最近记录: |