Angular2 linq样式属性访问器 [英] Angular2 linq style property accessor

查看:105
本文介绍了Angular2 linq样式属性访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我们会看到一个数组(IEnumerable)属性,需要提取特定的值。在c#中我们可以做类似的事情:

Often, we are presented with an array (IEnumerable) property that specific values need to be extracted. in c# we can do something similar to:

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

是否有在Angular 2中轻松实现此目的的方法吗?

Is there a way to easily to this within Angular 2?

推荐答案

Lodash 为LINQ for JavaScript程序提供了类似的功能(然后是一些),虽然不是延迟执行 - LINQ查询被推迟到枚举之前,而lodash(通常)立即执行查询并返回数组/结果对象。 (虽然在这种情况下LINQ甚至不推迟它,因为 FirstOrDefault 返回标量而不是可查询/可枚举。)

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. (Though in this case LINQ wouldn't even defer it since FirstOrDefault returns a scalar and not a queryable/enumerable.)

在你的情况下,你会做这样的事情:

In your case, you would do something like this:

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

    // ...
};

然后访问 obj.promoImage 将执行函数获取属性的值。

Then accessing obj.promoImage will execute the function to obtain the attribute's value.

(这里我假设这是我们创建新对象的地方,资产是构造函数的词法范围中的资产列表。如果要在对象本身而不是构造函数upvalues中存储数据,可以将其更改为引用 this 。)

(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.)

注意:


  • Lodash根本不依赖于Angular。

  • ES6提供了 find() 方法,因此这个功能将内置于浏览器一次ES6被采用。可悲的是,IE(像往常一样)是异常值,没有任何支持。但是,Lodash仍然是一个非常有用的工具包库,请注意Lodash的 find()也适用于对象,而不仅仅是数组。

  • Lodash does not depend on Angular at all.
  • ES6 provides a find() method on the Array prototype, so this feature will be built-in to browsers once ES6 is adopted. Sadly, IE is (as usual) the outlier without any support for it. 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.

这篇关于Angular2 linq样式属性访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆