首页 文章

覆盖自定义typescript类中的javascript对象toString()

提问于
浏览
2

我似乎在任何地方都能获得解决方案 . Background :我有一个typescript类定义如下:

export class Client extends Person {
    claimNumber: string;
    policyNumber: string;
    address: string;
    insuranceCompany: Organisation = new Organisation();

    toString(): string {
        return this.policyNumber
            .concat(this.claimNumber);
    }
}

以上用作驱动角度5模板的模型 . 在我的组件中,我从远程api获取(使用angular 5 HttpClient )客户端列表并生成html表行 . 生成表行的LOC是:

<tr *ngFor="let client of clients | filter:searchString"> ... </tr>

searchString 以上是绑定到搜索输入标记的属性& filter 是自定义过滤器管道,定义如下:

export class FilterPipe implements PipeTransform {
    transform(items: Client[], term: string) {               
        if (term == undefined || term === '') return items;
        return items.filter(item =>item.toString().toLocaleLowerCase().includes(term.toLocaleLowerCase()));
    }
}

Problem :当我在上面的过滤器管道中检查item.toString()时,它返回[object Object]而不是由policyNumber和claimNumber组成的字符串 .

Investigation :我按如下方式调查了这个问题:我按如下方式实例化了Client类:

let c = new Client();
c.policyNumber = 'ababababa';
c.claimNumber = 'aaaaaaa';
console.log('client toString() is => ' + c.toString());

有趣的是,上面的console.log输出:'ababababaaaaaaa' .

Question :我做错了导致过滤器管道中的item.toString()返回 [object Object] 而实例化的类上的toString()返回正确的字符串?

2 回答

  • 0

    如果您从WebService(或类似的东西)获得客户端,那么您将获得 plain json objects . 如果你说收到的对象是 Client 类型,typescript会将它们显示为这种类型的对象,但是 only the properties 将是相同的,方法不是来自 Client 类,而是来自 Object 类 .

    从服务器检索它们后,您可能希望将它们实例化为真正的客户端对象:

    public myServiceMethod() {
        return this.http.get(...).map(plainClients => {
            const realClients: Array<Client> = (plainClients || []).map(plainClient => {
                let realClient = new Client();
                realClient.claimNumber = plainClient.claimNumber;
                realClient.policyNumber = plainClient.policyNumber;
                realClient.address = plainClient.address;
                return realClient;
            });
            return realClients;
        })
    }
    

    您可能更喜欢使用贫血对象,其类型为接口,并使用实用函数将客户端检索为字符串,以避免像您所拥有的那样:

    export interface Person {
        ...
    }
    
    export interface Client extends Person {
        claimNumber: string;
        policyNumber: string;
        address: string;
        insuranceCompany: Organisation;
    }
    
    // In some utilitarian class
    public static getClientInfo(client: Client) {
        return client.policyNumber.concat(client.claimNumber);
    }
    
    // In your pipe
    return items.filter(item => getClientInfo(item).toLocaleLowerCase().includes(term.toLocaleLowerCase()));
    

    我并不是说在您的应用程序中使用贫血类,但如果某种类型的对象被传递并且可能会被序列化,那么使用贫血对象可以避免像您所拥有的那样的问题 .

  • 1

    找出问题可能的方法是将方法重命名为不是内置方法名称的东西,例如 toSearchString . 将控制台日志添加到过滤器功能中也是值得的,以确保您实际上在那里获得 clients . 你可能实际上得到了一个不同的对象 .

相关问题