typescript 如何订阅数组更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38654717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:41:53  来源:igfitidea点击:

How to subscribe to array change?

typescriptangularrxjs

提问by uksz

I am wondering if it's possible to subscribe to a change object, that is an array. My use case is the following: user reloads a page, that requires the whole collection to be loaded, and then get one object with a specific id. As I know, I can create a function like this:

我想知道是否可以订阅更改对象,即一个数组。我的用例如下:用户重新加载一个页面,这需要加载整个集合,然后获取一个具有特定 id 的对象。据我所知,我可以创建一个这样的函数:

In constructor:

在构造函数中:

this.getById(id);

And the function

和功能

getById(id: string){
    this.object = this.objectsService.getById(id);
    if (this.object.name){ //check if object exist
        //Do something
    } else {
        setTimeout(()=>{
            this.getById(id)
        }, 1000);
    }
}

However, I got a feeling that this is not the best thing to do. So, what I would like to do is something like this:

但是,我有一种感觉,这不是最好的做法。所以,我想做的是这样的:

let objects = this.objectService.getObjects() // returns object that will hold the collection;
objects.subscribe((value) => { 
    if(value.length) {
        //Do something
    }
});

采纳答案by Toan Nguyen

You can store a reference to your data arrayinstead of Observable. For example when the call from the http service return with Observable, you can do

您可以存储对数据数组的引用而不是Observable。例如,当来自 http 服务的调用返回Observable 时,您可以这样做

function getObjects:Promise<Item[]>{
        return this.http.get(this.apiUrl)
                      .toPromise()
                      .then(this.extractData)
    }

    private extractData(res: Response) {
      let body = res.json();
      return body.data || { };
    }

In your component class, you can store data like this:

在您的组件类中,您可以像这样存储数据:

this.objectService.getObjects().then(items=> this.items = items);

Next, when you need to get an item by its id, you can do:

接下来,当您需要通过id获取项目时,您可以执行以下操作:

let currentItem = this.items.filter(x=> x.id == currentId)

By doing that way you have the list cached when your page loads and have the value ready when users's selection is changed.

通过这样做,您可以在页面加载时缓存列表,并在用户选择更改时准备好值。

回答by Dylan Meeus

If I am understanding your question correctly, you are looking to create an observable from an array so you can subscribe to it? If so, you might be looking for Rx.Observable.from(iterable, [mapFn], [thisArgs],[scheduler]. There is a page in the rxjs docsabout this.

如果我正确理解了您的问题,您是否希望从数组中创建一个 observable 以便您可以订阅它?如果是这样,您可能正在寻找 Rx.Observable.from(iterable, [mapFn], [thisArgs],[scheduler]. rxjs 文档中有一个关于此的页面。

It creates an observable from an Array, to which you can then subscribe.

它从一个 Array 创建一个 observable,然后你可以订阅它。

Something like this might be what you are looking for

像这样的东西可能是你正在寻找的

 Rx.Observable.from([1,2,3]).subscribe(x => // do something with x);

Subscribe to changing array

订阅更改数组

As pointed out in the comments, the above approach subscribes to the array and observes the values that are currently in the array, but it does not deal with changes to this Array.

正如评论中所指出的,上述方法订阅数组并观察数组中当前的值,但它不处理对此数组的更改。

Perhaps an approach here would be to create a subject, and observe the subject. Instead of pushing values to the existing arrays, you push values to the Subject (which holds basically an array of the elements). When you push to the Subject, you generate an event that can be caught by a subscriber.

也许这里的一种方法是创建一个主题,然后观察这个主题。不是将值推送到现有数组,而是将值推送到主题(它基本上包含一个元素数组)。当您推送到主题时,您会生成一个可由订阅者捕获的事件。