是否可以在Angular 2的代码中使用管道?

Hon*_*iao 87 angular-pipe angular

当我在模板中使用自定义管道时,就像这样.它运作良好.

{{user|userName}}
Run Code Online (Sandbox Code Playgroud)

是否可以在代码中使用管道?我试着这样用,

let name = `${user|userName}`;
Run Code Online (Sandbox Code Playgroud)

但它表明

userName未定义

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

Hon*_*iao 101

@Siva是对的.谢谢!

因此在组件中使用管道的方式如下:

let name = new UserNamePipe().transform(user);
Run Code Online (Sandbox Code Playgroud)

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

  • 这可行,但是可能不遵循Angular最佳实践/首选模式。如另一个答案所示,将管道作为组件依赖项传递到构造函数中是“更正确的选择”。 (3认同)
  • 这是使用管道的完全错误的方式。管道是**特殊**用途的类,应通过 Angular 提供的特殊方式使用。如果您需要在管道中实现某些功能,但需要像常规 TypeScript 类一样使用它,那么您必须创建该 `regular` 类并在您的 TS 代码中使用它(例如,`your-component.ts` )。如果您需要管道中的相同功能,您始终可以使用管道中的“常规”类。 (3认同)

sag*_*aei 85

这是您在组件中使用Pipe的方法:

import { YourPipeComponentName } from 'your_component_path';

@NgModule({
  providers: [
    YourPipeComponentName
  ]
})
export class YourServiceModule {
}
Run Code Online (Sandbox Code Playgroud)

  • @Sam确实需要在`provider`中.将`YouPipeComponentName`添加到`providers`中,此方法将完美运行. (19认同)
  • 还要确保将其添加到正确的提供程序.如果要全局使用管道,请将其放在app.module提供程序中.如果您只想在一些延迟加载的模块中使用它,请将其放在各自模块的提供程序中 (4认同)