有可能在代码中使用管道吗?

当我在模板中使用自定义管道时,它是这样的:

{{user|userName}}

而且效果很好。

有可能在代码中使用管道吗?

我试着这样使用它:

let name = `${user|userName}`;

但是看得出来

UserName 未定义

我的替代方法是在代码中手动使用 db.collection.findOne()。但是有什么聪明的方法吗?

99730 次浏览

@ 湿婆说得对,谢谢!

所以在组件中使用管道的方法是这样的:

let name = new UserNamePipe().transform(user);

链接到另一个类似的问题。

首先在模块的 providers中声明管道:

import { YourPipeComponentName } from 'your_component_path';


@NgModule({
providers: [
YourPipeComponentName
]
})
export class YourServiceModule {
}

然后你可以在这样的组件中使用 @Pipe:

import { YourPipeComponentName } from 'your_component_path';


class YourService {


constructor(private pipe: YourPipeComponentName) {}


YourFunction(value) {
this.pipe.transform(value, 'pipeFilter');
}
}