Angular 2如何更新Observables数组?

时间:2019-03-24 14:08:17

标签: javascript angular typescript nativescript

堆栈:Angular,Nativescript, Typescript

我从localStorage获取ID,然后为每个id调用HTTP请求以从API获取该项目。一切正常,但我想使ID(LocalStorageArray的ID和Http请求中的项目)都成为订阅,并且它们会监视更改。例如:如果有新的localStorage ID,它将从该ID调用HTTP,然后将其添加到我的observable array中。

我的示例有效,但没有达到我的期望,因为在我向ObservableArray添加项目后,它没有更新localStorage。我在StackOverflow上搜索了有关如何订阅数组并在每次更改时调用一个函数的答案,但是都没有帮助。我查看过的链接:

https://docs.nativescript.org/angular/ui/professional-ui-components/ng-ListView/getting-started

https://appdividend.com/2018/12/08/angular-7-observables-tutorial-with-example/

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent

我的示例:

Home.component.ts:

data;
    public filteredItems : ObservableArray<Observable> = new ObservableArray([]);
    localStorageArray = [];
 public getStorageArray(){
     this.localStorageArray = new Array;
        console.log(localStorage.length)
        for (let i = 0; i < localStorage.length; i++) {
            let key = localStorage.key(i);
            let val = localStorage.getItem(key);
            this.localStorageArray.push(val);
        }
        console.log('Local storage array', this.localStorageArray);
        if(this.localStorageArray.length != 0) {
            this.getFavorites(this.localStorageArray);
        }
    }

    getFavorites(eanArray){
        if(this.localStorageArray.length > 1){
            this.data = this.dataService.getProductsByEan(eanArray).subscribe
            ((data: any) => {
                    this.filteredItems = data['hydra:member'];
                    console.log(this.filteredItems.length);
            }, (error) => {
                console.log(error)
            }, () => {
                console.log('favorites succes')
            });
        }
      }

然后我尝试从另一个组件更新this.filteredItems

List.component.ts:

providers: [HomeComponent],
constructor(private home: HomeComponent){}

1。什么也没发生,它没有更新:

updatefilteredItems(item){
console.log(this.home.filteredItems.length) --> 0 , but it has items.
this.home.filteredItems.push(item)
console.log(this.home.filteredItems.length) --> 1 , but it has more items.
}
  1. 什么也没有发生,它不是更新的:
updatefilteredItems(){
this.home.getStorageArray();
}

我希望当我更新this.filteredItems时会更新它,但是没有。

0 个答案:

没有答案