【问题标题】:Is it possible to override the built-in Angular 2 pipes so they can be used globally?是否可以覆盖内置的 Angular 2 管道,以便它们可以在全球范围内使用?
【发布时间】:2016-01-27 17:26:13
【问题描述】:

我想覆盖“日期”管道,并像内置管道一样享受全局访问的好处——也就是避免在每个组件注释中导入和使用管道[]数组。这可能吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    是的,您可以使用 PLATFORM_PIPES 添加自定义管道并将该管道命名为 date 以劫持它。

    @Pipe({
       name : 'date' // Hijacks the 'date' pipe
    })
    class CustomDatePipe {
      transform(val, args) {
        return /* do something new with the value */;
      }
    }
    
    @Component({
      selector: 'my-app',
      template : '{{mydate | date}}',
    })
    export class App {
      mydate = Date.now();
    }
    
    // Provides the CustomDatePipe globally
    bootstrap(App, [provide(PLATFORM_PIPES, {useValue: [CustomDatePipe], multi: true})]);
    

    这样您就不必每次都在组件的pipes 属性中添加指定它。

    这是一个plnkr ,其中有一个示例。

    【讨论】:

    • 你知道需要做什么才能使管道在单元测试中也全局可用吗?
    【解决方案2】:

    Eric Martinez 的回答效果很好!请记住 PLATFORM_PIPES 在 Angular4 中已弃用。 Angular4 中的平台管道是通过 app.modules 配置的:

    /**
     * `AppModule`
     */
     @NgModule({
        ...
        providers: [
           ...
           CustomDatePipe
        ]
    })
    

    【讨论】:

    • 对于测试(回答 Vilmantas Baranauskas 的问题):您可以为 Pipe 本身编写测试,并在测试中显式调用转换,例如新的 CustomDatePipe().transform(input)
    • 已弃用!解决方案见stackoverflow.com/a/56020657/9224219
    【解决方案3】:

    是的,请按以下方式使用 PLATFORM_PIPES

    https://angular.io/docs/ts/latest/api/core/index/PLATFORM_PIPES-let.html

    import {PLATFORM_PIPES} from '@angular/core';
    import {OtherPipe} from './myPipe';
    @Component({
      selector: 'my-component',
      template: `
        {{123 | other-pipe}}
      `
    })
    export class MyComponent {
      ...
    }
    bootstrap(MyComponent, [{provide: PLATFORM_PIPES, useValue: [OtherPipe], multi:true}]);
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2017-01-03
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多