【发布时间】:2018-07-03 02:10:10
【问题描述】:
我想在 Injectable 服务中调用我的自定义管道。我检查了stackoverflow中的许多线程。但是他们谈论在组件内使用自定义管道。你能在这里帮助我吗,任何有用的链接都可以。 以下是我的自定义管道文件:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'unit' })
export class UnitPipe implements PipeTransform {
transform(val,unit, args) {
if(unit=='Metric') {
return val * 2;
}
else {
return val * 4;
}
}
}
我正在尝试在我的服务中访问此管道:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { UnitPipe } from '../pipes/UnitPipe';
@Injectable()
export class SomeService {
constructor(http: Http, unitPipe: UnitPipe) {
this.http = http;
this.unitPipe = unitPipe;
}
transformUnit() {
return this.unitPipe.transform('10', 'Metric');
}
}
我已经在 app.module.js
中指定了这个declarations: [UnitPipe],
providers: [UnitPipe]
在我的 component.js 中,我正在调用此服务方法并仅检查控制台中的输出:
import { Component, OnInit, EventEmitter, Input } from '@angular/core';
import { SomeService } from '../../services/SomeService';
@Component({
})
export class SomeClass implements OnInit {
constructor(someService: SomeService) {
this.someService = someService;
}
ngOnInit(): void {
console.log(this.someService.transformUnit());
}
}
但是我遇到了错误
还有一件事是,我的计划是在我的服务文件“SomeService”中调用 transformUnit 方法,可能是 onload,其中存在函数定义。对此有什么想法吗?
谢谢。
【问题讨论】:
-
贴出一些你尝试过的代码,以便于理解你的问题
-
添加了代码。谢谢。
标签: angular2-pipe