[英]Angular Inject Pipe in Service
我已经创建了以下用于格式化数据的服务。 从角度组件调用该服务, guest.vo.ts
返回已处理的数据
import { Guest } from '../core/guest/guest.model';
import { TimeAgoPipe } from 'angular2-moment/time-ago.pipe';
import { Injectable } from '@angular/core';
@Injectable()
export default class GuestVO {
constructor(private timeAgo: TimeAgoPipe) {}
getVO(guests: Guest[]) {
return guests.map(guest => {
let vo: any = {};
vo.created = this.timeAgo.transform(guest.created);
return vo;
});
}
}
我正在使用下面的库进行时间计算https://github.com/urish/angular2-moment/blob/master/src/time-ago.pipe.ts
但是,在将TimeAgoPipe注入Service时遇到了错误,因为它取决于ChangeDetectorRef。
如果我直接在Component中使用TimeAgoPipe,则不会发生此问题。 有关使用此管道的任何建议?
constructor(
private cdRef: ChangeDetectorRef,
private ngZone: NgZone) {
}
管道 -s是不可注入的。 您可以将其添加到模块的declarations
中并使用它。 如果要注入管道,可以将其作为服务提供,例如
{ provide: MyPipe, useClass: TimeAgoPipe }
并将其实例注入为MyPipe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.