情况:
我只需要在一个组件中使用管道。出于这个原因,我不想全局导入它,只能在组件中导入。
我试过寻找有关如何操作的参考,但找不到它。
这是我的尝试:
THE PIPE:
全球测试时工作正常
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any
{
let keys = [];
for (let key in value)
{
keys.push({key: key, value: value[key]});
}
return keys;
}
}
组件:
import { Component, NgModule } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {CommonModule} from "@angular/common";
import { KeysPipe } from './keys.pipe';
@Component({
selector: 'page-attendees',
templateUrl: 'attendees.html'
})
@NgModule({
declarations: [ KeysPipe ],
imports: [ CommonModule ],
exports: [ KeysPipe ]
})
export class AttendeesPage {
public attendeeList = [];
public arrayOfKeys;
constructor(
public navCtrl: NavController,
public navParams: NavParams
) {
this.attendeeList = this.navParams.get('attendeeList');
this.arrayOfKeys = Object.keys(this.attendeeList);
}
ionViewDidLoad() {
console.log('AttendeesPage');
}
}
错误:
Unhandled Promise rejection: Template parse errors:
The pipe 'keys' could not be found
PLUNKER:
https://plnkr.co/edit/YJUHmAkhAMNki2i6A9VY?p=preview
问题:
你知道我做错了什么或者我错过了什么吗?
谢谢!
答案 0 :(得分:0)
您可以在组件中的providers
数组中定义管道,而不是在constructor
中声明它,最后在组件中使用它。
import { Component, NgModule } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {CommonModule} from "@angular/common";
import { KeysPipe } from './keys.pipe';
@Component({
selector: 'page-attendees',
templateUrl: 'attendees.html',
providers: [ KeysPipe ]
})
@NgModule({
imports: [ CommonModule ],
})
export class AttendeesPage {
public attendeeList = [];
public arrayOfKeys;
keys;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private keysPipe: KeysPipe
) {
this.attendeeList = this.navParams.get('attendeeList');
this.arrayOfKeys = Object.keys(this.attendeeList);
this.keys = this.keysPipe(this.arrayOfKeys, this.attendeeList)
}
ionViewDidLoad() {
console.log('AttendeesPage');
}
}