简体   繁体   English

Angular2 Linq样式属性访问器

[英]Angular2 linq style property accessor

Often, we are presented with an array (IEnumerable) property that specific values need to be extracted. 通常,我们会遇到需要提取特定值的数组(IEnumerable)属性。 in c# we can do something similar to: 在C#中,我们可以执行以下操作:

public AssetModel PromoImage {
        get
        {
            return Assets.FirstOrDefault(x => x.AssetTypeCd == "promoimage");
        }
        private set { }
    }

Is there a way to easily to this within Angular 2? 有没有办法在Angular 2中轻松做到这一点?

Lodash provides similar functionality to LINQ for JavaScript programs (and then some), though not deferred execution -- LINQ queries are deferred until they are enumerated, while lodash (usually) performs the query immediately and returns an array/object of results. Lodash为JavaScript程序(以及某些功能)提供了与LINQ类似的功能,尽管没有延迟执行-LINQ查询被延迟直到被枚举,而lodash(通常)会立即执行查询并返回结果数组/对象。 (Though in this case LINQ wouldn't even defer it since FirstOrDefault returns a scalar and not a queryable/enumerable.) (尽管在这种情况下,LINQ甚至不会推迟它,因为FirstOrDefault返回标量,而不是可查询/可枚举的对象。)

In your case, you would do something like this: 对于您的情况,您将执行以下操作:

let obj = {
    get promoImage() {
        return _.find(assets, a => a.assetTypeCd === 'promoimage');
    },

    // ...
};

Then accessing obj.promoImage will execute the function to obtain the attribute's value. 然后访问obj.promoImage将执行该函数以获取属性的值。

(Here I assume this is where we are creating the new object, and assets is the assets list in the lexical scope of the constructor function. You can change it to reference this if you are storing data on the object itself and not in constructor upvalues.) (这里我假设这是我们创建新对象的地方, assets是构造函数的词法作用域中的资产列表。如果您将数据存储在对象本身上而不是在构造函数上值中,则可以更改它以引用this对象)


Notes: 笔记:

  • Lodash does not depend on Angular at all. Lodash完全不依赖Angular。
  • ES6 provides a find() method on the Array prototype, so this feature will be built-in to browsers once ES6 is adopted. ES6在Array原型上提供了find()方法,因此一旦采用ES6,此功能将内置于浏览器中。 Sadly, IE is (as usual) the outlier without any support for it. 可悲的是,IE(通常)是离群值,没有任何支持。 However, Lodash is still a very useful library to have in your toolkit, and note that Lodash's find() works on objects too, not just arrays. 但是,Lodash仍然是您工具箱中非常有用的库,请注意,Lodash的find()可用于对象,而不仅仅是数组。

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

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