【问题标题】:Pipes within components from shared module来自共享模块的组件内的管道
【发布时间】:2018-04-25 18:14:00
【问题描述】:

我一直在 NG 中构建自己的应用程序,并在共享模块中使用组件中的管道遇到问题。

共享模块(删除所有其他内容):

import { NgModule } from '@angular/core';
import { FilterByPipe, OrderByPipe } from './pipes/index';


@NgModule({
    imports: [],
    declarations: [FilterByPipe],

    exports: [
        //Pipes
        FilterByPipe,
    ],

    providers: [FilterByPipe]

})
export class SharedModule { }

我的问题是,如何在另一个组件代码中使用导出的管道FilterByPipe?即

export class ViewSomethingComponent implements OnInit {
    constructor(private _filterBy: FilterByPipe)

    filterSomething(data){ this._filterBy.transform(data,{a:'value'})}
}

我尝试过直接导入管道,但这给了我依赖问题,因为它不是从父模块提供的。除了将pip添加到父模块中,然后将其用作依赖注入的提供者之外,没有其他方法可以使用共享组件导出的管道吗?

【问题讨论】:

    标签: angular angular-components angular-pipe angular-module


    【解决方案1】:

    SharedModule 导入到您的根目录AppModule

    然后您可以轻松地在AppModule 内的任何组件中使用您的FilterByPipe

    import { FilterByPipe } from '@angular/common';
    class FilterByPipe {
      constructor(private fillterPipe: FilterByPipe) {}
      transformData(data) {
        this.fillterPipe.transform(data);
      }
    }
    

    并添加以下内容,否则会出错

    providers: [FilterByPipe] 
    

    【讨论】:

    • 虽然我可以在 HTML ('{{somedata | filterby: 'value'}}') 中使用管道,但在尝试将其注入控制器时,它会返回一个找不到类的错误。
    • 我已经更新了答案。如需更清晰的视图,请参阅:stackoverflow.com/questions/35144821/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多