Stack: Angular,Nativescript, Typescript
.
I am getting id's from localStorage
and then for each id
I am calling HTTP
request to get that item from API
. Everything works fine, but I want to make that both (LocalStorageArray
of id's and Items from Http
request) would be subscriptions and they would watch for changes. For example: if there are new localStorage
id, it would call HTTP
from that id and then add to my observable array
.
My example works but not as I want, because it isn't updating my ObservableArray
after I add an item to my localStorage
. I searched for answers on StackOverflow how to subscribe to the array and call a function every time it changes, but neither helped. Links I viewed :
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/
My example :
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')
});
}
}
And then I am trying to update this.filteredItems
from another component :
List.component.ts :
providers: [HomeComponent],
constructor(private home: HomeComponent){}
1.nothing happens, it isnt updating :
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.
}
- nothing happens, it isnt updating :
updatefilteredItems(){
this.home.getStorageArray();
}
I expected that when I update this.filteredItems
it would update it, but it didn't.