【问题标题】:Entity list by parent entity and dotted paths按父实体和虚线路径列出的实体列表
【发布时间】:2018-04-03 20:00:04
【问题描述】:

我正在使用 Angular 5 + Breeze JS + 微风-bridge2-angular。

假设我们有一个Company 实体,它具有多个AddressAddress 实体类型的导航属性,而它自己又具有一些导航属性,例如Country 等:

import { Entity } from "breeze-client"; // From https://www.npmjs.com/package/breeze-client package 

export class Company implements Entity {
    billingAddress: Address;
    shippingAddress: Address;
}

export class Address implements Entity {
    country1: Country;
    country2: Country;
}

export class Country implements Entity {
    ...
}

所有实体都已查询到EntityMnager,无需从服务器查询任何内容。

如何实现一个方法(可能使用我目前缺少的一些 Breeze JS API) 采用父 Company 实体和一个带点属性路径的 string[] 并返回一个平面 @ 987654330@ 包含父实体和使用这些虚线路径定位的所有子实体的列表?

虚线路径与我们在 Breeze 查询中使用 expand() 方法相同(请参阅虚线展开路径 here),即:

const company: Company = ...; // Query Company and its children into EntityManager
const paths: string[] = [
    "billingAddress",
    "shippingAddress",
    "billingAddress.country1",
    "billingAddress.country2"];

getEntitiesFlat(entity: Entity, paths: string[]): Entity[] {
    // Not sure how to implement getChildren() method below
    const childEntities: Entity[] = this.getChildren(entity, paths);

    return [entity].concat(childEntities);
}

顺便说一句,我正在尝试删除父实体及其特定子实体,以上是迄今为止我受到 DevForce 框架启发的最简洁的方法。我们非常欢迎更好的想法。

【问题讨论】:

    标签: javascript angular typescript breeze devforce


    【解决方案1】:

    真的确定你在找什么。假设您使用 path 并将这些路径映射到 entity 对象...我想出了:

    function getByPath(entity: any, path: string) {
      if (!entity) return undefined
    
      const parts = path.split(".")
    
      if (parts.length === 1) {
        return entity[path]
      }
    
      return getByPath(entity[parts[0]], parts.slice(1).join("."))
    }
    

    使用喜欢

    const paths = ["a", "a.b.c", "a.b.d", "d", "c", "d.c"]
    const entity = {
      a: { b: { c: 1 } },
      b: 1,
      c: 2
    }
    
    paths.map(path => getByPath(entity, path)) // [ { b: { c: 1 } }, 1, undefined, undefined, 2, undefined ]
    

    编辑:如果您已经在使用lodash,只需使用lodash#get

    【讨论】:

    • 好主意,谢谢!如果没有人提出使用一些 Breeze JS API 而不是手动解析路径的解决方案,我会接受你的实现。
    • 对不起!我错过了你评论的那部分!我不熟悉微风。
    • 不,请原谅我 - 我在你回复后添加了那部分,因为我显然未能准确解释我所追求的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2011-09-02
    • 1970-01-01
    • 2015-10-28
    • 2015-12-14
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多