加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – 如何订阅数组更改?

发布时间:2020-12-17 08:47:03 所属栏目:安全 来源:网络整理
导读:我想知道是否可以订阅更改对象,即数组.我的用例如下:用户重新加载一个页面,需要加载整个集合,然后获取一个具有特定id的对象.据我所知,我可以创建一个这样的函数: 在构造函数中: this.getById(id); 和功能 getById(id: string){ this.object = this.object
我想知道是否可以订阅更改对象,即数组.我的用例如下:用户重新加载一个页面,需要加载整个集合,然后获取一个具有特定id的对象.据我所知,我可以创建一个这样的函数:

在构造函数中:

this.getById(id);

和功能

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);
    }
}

但是,我觉得这不是最好的事情.所以,我想做的是这样的事情:

let objects = this.objectService.getObjects() // returns object that will hold the collection;
objects.subscribe((value) => { 
    if(value.length) {
        //Do something
    }
});
您可以存储对数据数组的引用,而不是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 || { };
    }

在组件类中,您可以存储如下数据:

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读