简体   繁体   English

找不到管道 ' ' angular2 自定义管道

[英]The pipe ' ' could not be found angular2 custom pipe

I can't seem to fix this error.我似乎无法修复此错误。 I have a search bar and an ngFor.我有一个搜索栏和一个 ngFor。 I am trying to filter the array using a custom pipe like this:我正在尝试使用这样的自定义管道过滤数组:

import { Pipe, PipeTransform } from '@angular/core';

import { User } from '../user/user';

@Pipe({
  name: 'usersPipe',
  pure: false
})
export class UsersPipe implements PipeTransform {
  transform(users: User [], searchTerm: string) {
    return users.filter(user => user.name.indexOf(searchTerm) !== -1);
  }
}

Usage:用法:

<input [(ngModel)]="searchTerm" type="text" placeholder="Search users">

<div *ngFor="let user of (users | usersPipe:searchTerm)">
...
</div>

Error:错误:

zone.js:478 Unhandled Promise rejection: Template parse errors:
The pipe 'usersPipe' could not be found ("
<div class="row">
    <div  
    [ERROR ->]*ngFor="let user of (user | usersPipe:searchTerm)">

Angular versions:角度版本:

"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-rc.1",
"@angular/forms": "0.3.0",
"@angular/http": "2.0.0-rc.5",
"es6-shim": "^0.35.0",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.26",
"bootstrap": "^3.3.6",
"zone.js": "^0.6.12"

Make sure you are not facing a "cross module" problem确保您没有面临“跨模块”问题

If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.如果正在使用管道的组件不属于已“全局”声明管道组件的模块,则未找到管道并且您会收到此错误消息。

In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.在我的例子中,我在一个单独的模块中声明了管道,并将这个管道模块导入到任何其他具有使用管道组件的模块中。

I have declared a that the component in which you are using the pipe is我已经声明您使用管​​道的组件是

the Pipe Module管道模块

 import { NgModule }      from '@angular/core';
 import { myDateFormat }          from '../directives/myDateFormat';

 @NgModule({
     imports:        [],
     declarations:   [myDateFormat],
     exports:        [myDateFormat],
 })

 export class PipeModule {

   static forRoot() {
      return {
          ngModule: PipeModule,
          providers: [],
      };
   }
 } 

Usage in another module (eg app.module)在另一个模块中的使用(例如 app.module)

  // Import APPLICATION MODULES
  ...
  import { PipeModule }    from './tools/PipeModule';

  @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

You need to include your pipe in module declaration:您需要在模块声明中包含您的管道:

declarations: [ UsersPipe ],
providers: [UsersPipe]

For Ionic you can face multiple issues as @Karl mentioned.对于 Ionic,您可能会遇到@Karl 提到的多个问题。 The solution which works flawlessly for ionic lazy loaded pages is:对于离子延迟加载页面完美无缺的解决方案是:

  1. Create pipes directory with following files: pipes.ts and pipes.module.ts使用以下文件创建管道目录: pipes.tspipe.module.ts

// pipes.ts content (it can have multiple pipes inside, just remember to // pipe.ts 内容(里面可以有多个管道,只要记住

use @Pipe function before each class)
import { PipeTransform, Pipe } from "@angular/core";
@Pipe({ name: "toArray" })
export class toArrayPipe implements PipeTransform {
  transform(value, args: string[]): any {
    if (!value) return value;
    let keys = [];
    for (let key in value) {
      keys.push({ key: key, value: value[key] });
    }
    return keys;
  }
}

// pipes.module.ts content // pipe.module.ts 内容

import { NgModule } from "@angular/core";
import { IonicModule } from "ionic-angular";
import { toArrayPipe } from "./pipes";

@NgModule({
  declarations: [toArrayPipe],
  imports: [IonicModule],
  exports: [toArrayPipe]
})
export class PipesModule {}
  1. Include PipesModule into app.module and @NgModule imports section将 PipesModule 包含到 app.module 和 @NgModule 导入部分

    import { PipesModule } from "../pipes/pipes.module"; @NgModule({ imports: [ PipesModule ] });

  2. Include PipesModule in each of your .module.ts where you want to use custom pipes.在您要使用自定义管道的每个 .module.ts 中包含 PipesModule。 Don't forget to add it into imports section.不要忘记将其添加到导入部分。 // Example. // 示例。 file: pages/my-custom-page/my-custom-page.module.ts文件:pages/my-custom-page/my-custom-page.module.ts

    import { PipesModule } from "../../pipes/pipes.module"; @NgModule({ imports: [ PipesModule ] })

  3. Thats it.就是这样。 Now you can use your custom pipe in your template.现在您可以在模板中使用自定义管道。 Ex.例如。

<div *ngFor="let prop of myObject | toArray">{{ prop.key }}</div>

I found the "cross module" answer above very helpful to my situation, but would want to expand on that, as there is another wrinkle to consider.我发现上面的“跨模块”答案对我的情况非常有帮助,但我想对此进行扩展,因为还有另一个问题需要考虑。 If you have a submodule, it also can't see the pipes in the parent module in my testing.如果你有一个子模块,它在我的测试中也看不到父模块中的管道。 For that reason also, you may need to put pipes into there own separate module.出于这个原因,您可能需要将管道放入单独的模块中。

Here's a summary of the steps I took to address pipes not being visible in the submodule:以下是我为解决子模块中不可见的管道而采取的步骤的摘要:

  1. Take pipes out of (parent) SharedModule and put into PipeModule从(父)SharedModule 中取出管道并放入 PipeModule
  2. In SharedModule, import PipeModule and export (for other parts of app dependent on SharedModule to automatically gain access to PipeModule)在 SharedModule 中,导入 PipeModule 并导出(对于依赖 SharedModule的应用程序的其他部分,自动获取对 PipeModule 的访问权限)
  3. For Sub-SharedModule, import PipeModule, so it can gain access to PipeModule, without having to re-import SharedModule which would create a circular dependency issue, among other problems.对于 Sub-SharedModule,导入 PipeModule,这样它就可以访问 PipeModule,而无需重新导入 SharedModule,这会产生循环依赖问题等问题。

Another footnote to the above "cross module" answer: when I created the PipeModule I removed the forRoot static method and imported PipeModule without that in my shared module.上述“跨模块”答案的另一个脚注:当我创建 PipeModule 时,我删除了 forRoot 静态方法并在我的共享模块中导入了 PipeModule 而没有该方法。 My basic understanding is that forRoot is useful for scenarios like singletons, which don't apply to filters necessarily.我的基本理解是 forRoot 对于单例这样的场景很有用,这些场景不一定适用于过滤器。

Suggesting an alternative answer here:在这里建议一个替代答案:

Making a separate module for the Pipe is not required , but is definitely an alternative.不需要为 Pipe 制作一个单独的模块,但绝对是一个替代方案。 Check the official docs footnote: https://angular.io/guide/pipes#custom-pipes检查官方文档脚注: https : //angular.io/guide/pipes#custom-pipes

You use your custom pipe the same way you use built-in pipes.您可以像使用内置管道一样使用自定义管道。
You must include your pipe in the declarations array of the AppModule .您必须将管道包含在 AppModule 的声明数组中。 If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.如果你选择将你的管道注入到一个类中,你必须在你的 NgModule 的 providers 数组中提供它。

All you have to do is add your pipe to the declarations array, and the providers array in the module where you want to use the Pipe.您所要做的就是将您的管道添加到声明数组,以及您要使用管道的module中的提供者数组。

declarations: [
...
CustomPipe,
...
],
providers: [
...
CustomPipe,
...
]

Custom Pipes: When a custom pipe is created, It must be registered in Module and Component that is being used.自定义管道:创建自定义管道时,必须在正在使用的模块和组件中注册。

export class SummaryPipe implements PipeTransform{
//Implementing transform

  transform(value: string, limit?: number): any { 
    if (!value) {
        return null;
    }
    else {
        let actualLimit=limit>0?limit:50
       return value.substr(0,actualLimit)+'...'
    } 
  }
}

Add Pipe Decorator添加管道装饰器

 @Pipe({
        name:'summary'
    })

and refer并参考

import { SummaryPipe } from '../summary.pipe';` //**In Component and Module**
<div>
    **{{text | summary}}**  //Name should same as it is mentioned in the decorator.
</div>

//summary is the name declared in Pipe decorator //summary 是在 Pipe 装饰器中声明的名称

Note : Only if you are not using angular modules注意:仅当您不使用角度模块时

For some reason this is not in the docs but I had to import the custom pipe in the component出于某种原因,这不在文档中,但我必须在组件中导入自定义管道

import {UsersPipe} from './users-filter.pipe'

@Component({
    ...
    pipes:      [UsersPipe]
})

If you see this error when running tests, make sure you have imported the module the pipe belongs to, eg:如果您在运行测试时看到此错误,请确保您已导入管道所属的模块,例如:

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [CustomPipeModule],
            declarations: [...],
            providers: [...],
            ...
        }).compileComponents();
    }));

I have created a module for pipes in the same directory where my pipes are present我在管道所在的同一目录中为管道创建了一个模块

import { NgModule } from '@angular/core';
///import pipe...
import { Base64ToImage, TruncateString} from './'  

   @NgModule({
        imports: [],
        declarations: [Base64ToImage, TruncateString],
        exports: [Base64ToImage, TruncateString]
    })

    export class SharedPipeModule { }   

Now import that module in app.module:现在在 app.module 中导入该模块:

import {SharedPipeModule} from './pipe/shared.pipe.module'
 @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

Now it can be used by importing the same in the nested module现在可以通过在嵌套模块中导入相同的内容来使用它

import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'timePipe'
})
export class TimeValuePipe implements PipeTransform {

  transform(value: any, args?: any): any {
   var hoursMinutes = value.split(/[.:]/);
  var hours = parseInt(hoursMinutes[0], 10);
  var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
  console.log('hours ', hours);
  console.log('minutes ', minutes/60);
  return (hours + minutes / 60).toFixed(2);
  }
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  order = [
    {
      "order_status": "Still at Shop",
      "order_id": "0:02"
    },
    {
      "order_status": "On the way",
      "order_id": "02:29"
    },
    {
      "order_status": "Delivered",
      "order_id": "16:14"
    },
     {
      "order_status": "Delivered",
      "order_id": "07:30"
    }
  ]
}

Invoke this module in App.Module.ts file.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM