programing

파이프 ' '을(를) 찾을 수 없습니다. 각도2 사용자 지정 파이프

minimums 2023. 4. 28. 20:24
반응형

파이프 ' '을(를) 찾을 수 없습니다. 각도2 사용자 지정 파이프

저는 이 오류를 고칠 수 없을 것 같습니다.저는 검색창과 ngFor를 가지고 있습니다.다음과 같은 사용자 지정 파이프를 사용하여 배열을 필터링하려고 합니다.

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);
  }
}

용도:

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

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

오류:

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/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"

"교차 모듈" 문제가 발생하지 않았는지 확인합니다.

파이프를 사용하는 구성 요소가 파이프 구성 요소를 "전체적으로" 선언한 모듈에 속하지 않으면 파이프를 찾을 수 없고 이 오류 메시지가 표시됩니다.

저의 경우 파이프를 별도의 모듈에 선언하고 파이프를 사용하는 구성 요소가 있는 다른 모듈에서 이 파이프 모듈을 가져왔습니다.

나는 당신이 파이프를 사용하는 구성요소가

파이프 모듈

 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: [],
      };
   }
 } 

다른 모듈(예: app.module)의 사용량

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

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

모듈 선언에 파이프를 포함해야 합니다.

declarations: [ UsersPipe ],
providers: [UsersPipe]

Ionic의 경우 @Karl이 언급한 것처럼 여러 문제에 직면할 수 있습니다.이온성 지연 로드 페이지에서 완벽하게 작동하는 솔루션은 다음과 같습니다.

  1. pipes.ts pipes.module.ts 파일을 사용하여 파이프 디렉토리를 만듭니다.

pipes.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;
  }
}

파이프.contents 내용물

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. app.module 및 @NgModule 가져오기 섹션에 PipesModule 포함

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

  2. 사용자 지정 파이프를 사용할 각 .module.ts에 PipesModule을 포함합니다.수입 섹션에 추가하는 것을 잊지 마세요.예를 들면.파일: pages/my-custom-page/my-custom-page.ts

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

  3. 바로 그거야.이제 템플릿에서 사용자 정의 파이프를 사용할 수 있습니다.전.

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

저는 위의 "교차 모듈" 답변이 제 상황에 매우 도움이 된다는 것을 알았지만, 고려해야 할 또 다른 주름이 있기 때문에 이에 대해 더 자세히 설명하고 싶습니다.하위 모듈이 있는 경우 테스트에서 상위 모듈의 파이프도 볼 수 없습니다.따라서 별도의 모듈에 파이프를 삽입해야 할 수도 있습니다.

다음은 파이프가 하위 모듈에 표시되지 않는 문제를 해결하기 위해 수행한 단계를 요약한 것입니다.

  1. (상위) 공유 모듈에서 파이프를 꺼내 파이프 모듈에 넣습니다.
  2. Shared Module에서 PipeModule을 가져오고 내보냅니다(SharedModule에 종속된 앱의 다른 부분이 PipeModule에 자동으로 액세스할 수 있도록 하기 위해).
  3. 하위 공유 모듈의 경우 파이프 모듈을 가져오면 순환 종속성 문제 등을 발생시키는 공유 모듈을 다시 가져올 필요 없이 파이프 모듈에 액세스할 수 있습니다.

위의 "교차 모듈" 답변에 대한 또 다른 각주: 파이프 모듈을 만들 때 forRoot 정적 메서드를 제거하고 공유 모듈에 없는 파이프 모듈을 가져왔습니다.기본적으로 forRoot는 필터에 반드시 적용되지 않는 싱글톤과 같은 시나리오에 유용합니다.

여기서 대안을 제시합니다.

파이프에 대해 별도의 모듈을 만드는 은 필요하지 않지만 확실한 대안입니다.공식 문서 각주 확인: https://angular.io/guide/pipes#custom-pipes

기본 제공 파이프를 사용하는 것과 동일한 방식으로 사용자 지정 파이프를 사용합니다.
AppModule의 선언 배열에 파이프를 포함해야 합니다.파이프를 클래스에 주입하도록 선택한 경우 NgModule의 공급자 배열에 파이프를 제공해야 합니다.

당신이 해야 할 일은 당신의 파이프를 선언 배열과 공급자 배열에 추가하는 것입니다.module파이프를 사용할 위치.

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

테스트를 실행할 때 이 오류가 나타나면 파이프가 속한 모듈을 가져왔는지 확인하십시오. 예:

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

사용자 지정 파이프:사용자 정의 파이프를 작성할 때 사용 중인 모듈 및 구성요소에 등록해야 합니다.

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)+'...'
    } 
  }
}

파이프 장식기 추가

 @Pipe({
        name:'summary'
    })

및 참조

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

//summary는 파이프 장식가에 선언된 이름입니다.

참고: 각도 모듈을 사용하지 않는 경우에만 해당

어떤 이유로 문서에는 없지만 구성 요소에 있는 사용자 지정 파이프를 가져와야 했습니다.

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

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

저도 같은 문제에 직면한 적이 있습니다.

처음에는.a "cross module" problem여기에 기술된 바와 같이

그러나 이게 끝이 아니다.

응용 프로그램을 장시간 실행 중 - 앱이 이 새 가져온 파이프로 확인할 수 없습니다.

명령을 다시 실행합니다. 그리고 마지막으로.cross module요 ㅠㅠㅠㅠ

파이프가 있는 디렉터리에 파이프 모듈을 만들었습니다.

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

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

    export class SharedPipeModule { }   

이제 해당 모듈을 app.module로 가져옵니다.

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

이제 중첩된 모듈에서 동일한 항목을 가져와 사용할 수 있습니다.

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.

언급URL : https://stackoverflow.com/questions/39007130/the-pipe-could-not-be-found-angular2-custom-pipe

반응형