【问题标题】:Using Custom Pipes in services in angular2在angular2的服务中使用自定义管道
【发布时间】: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


【解决方案1】:

您的管道变换函数需要 3 个参数:

transform(val,unit, args) {
  ...
}

您只提供了 2 个参数:

transformUnit() {
    return this.unitPipe.transform('10', 'Metric');
}

我可以建议的最佳解决方案是使用 可选/默认 参数:

可选参数 - 将args更改为args?

默认参数 - 将args 更改为args = null // 或其他一些默认值

这将允许您使用 2 个参数调用管道函数,因此无需在您的服务中更改代码。

您可以在此TypeScirpt-Functions 链接中查看名为可选和默认参数的部分了解更多详细信息。

使用您的代码创建了一个简单的StackBlitz DEMO 以实现此目的。最初,您将在 SomeService 文件中看到错误。只需相应地更改管道args 参数即可。刷新页面。 SomeService 中的错误消失了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 2016-12-24
    • 2017-12-07
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2017-04-28
    相关资源
    最近更新 更多