简体   繁体   English

这是在Angular 2中实现Pipe的正确方法吗

[英]Is this the correct way to implement a Pipe in Angular 2

I am working on an Angular 2 application with Webpack. 我正在使用Webpack开发Angular 2应用程序。

I am implementing a pipe in Angular 2 to format phone number using google-libphonenumber. 我正在Angular 2中实现管道以使用google-libphonenumber格式化电话号码。 Everything is working as expected. 一切都按预期进行。 I am not very knowledgeable on how require works ie, it is as simple as using an existing JS function or loads a library doing an expensive operation. 我对需求如何工作不是很了解,例如,它就像使用现有的JS函数一样简单,或者加载一个执行昂贵操作的库。 So I'm not sure if I have to define PNF and phoneUtil in the example below, outside the transform function in pipe. 所以我不确定是否必须在下面的示例中在管道中的transform函数之外定义PNFphoneUtil

export class PhonePipe implements PipeTransform {
    transform(value: string) {
        let PNF = require('google-libphonenumber').PhoneNumberFormat;
        // Get an instance of `PhoneNumberUtil`.
        let phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
        // Add a leading '+' sign if not available. Assumption is all numbers contain country code prefixed.
        let newValue = value.length > 0 && value.charAt(0) != "+" ? "+" + value : value;
        // Format the number.
        let parsedPhoneObj = phoneUtil.parse(newValue, 'US');
        console.log(parsedPhoneObj);
        return phoneUtil.format(parsedPhoneObj, PNF.INTERNATIONAL);
    }
}

Will appreciate any suggestions. 将不胜感激任何建议。 My goal is optimize the application performance. 我的目标是优化应用程序性能。

I would do: 我会做:

import * as libphonenumber from 'google-libphonenumber';

export class PhonePipe implements PipeTransform {
    transform(value: string) {

        let PNF = libphonenumber.PhoneNumberFormat;

        // Get an instance of `PhoneNumberUtil`.
        let phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();

        // Add a leading '+' sign if not available. Assumption is all numbers contain country code prefixed.
        let newValue = value.length > 0 && value.charAt(0) != "+" ? "+" + value : value;

        // Format the number.
        let parsedPhoneObj = phoneUtil.parse(newValue, 'US');

        return phoneUtil.format(parsedPhoneObj, PNF.INTERNATIONAL);
    }
}

You don't really use require with typescript, instead you can use import as showed. 您实际上并没有在打字稿中使用require ,而是可以如图所示使用import。 This also gives you 1 import rather than 2 like you had before. 这也给您1次导入,而不是以前的2次。

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

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