堆栈: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/
我的示例:
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.
}
updatefilteredItems(){
this.home.getStorageArray();
}
我希望当我更新this.filteredItems
时会更新它,但是没有。