从另一个页面推送时,Angular Nativescript RadListView不更新

时间:2019-03-22 12:29:45

标签: angular typescript nativescript

我有RadListView,它从http请求中获取数据。 :

<RadListView #listView  separatorColor="transparent"
        pullToRefresh="true" (pullToRefreshInitiated)="refreshFavorites($event);" *ngIf="filteredItems && filteredItems.length; else noItems" row="2"
            [items]="filteredItems" marginTop="-100" (touch)="dismissKeyboard($event)">
    <ng-template let-item="item" let-i="index">
        <GridLayout columns="10,*,10">
            <GridLayout *ngIf="item" (tap)="goToInner(item)" [nsRouterLink]="['../favorite', item.ean]" pageTransition="slide"  shadow='6' cornerRadius='5' col="1" columns="*,auto" class="p-8 m-b-8 m-x-8" borderRadius="8"
            backgroundColor="white">
                <GridLayout class="favorite-card" col="0" columns="150,*,auto" rows="auto,auto,auto">
                    <Image col="0" rowSpan="3" class="thumbnail m-r-12" stretch="aspectFit" *ngIf="item.images"
                        [src]="item.images.large.url"></Image>
                        <StackLayout col="1" row="1" verticalAlingment="center">
                                <Label  class="h3 title m-t-4" marginBottom="0" textWrap="true" maxLines="2" [text]="item.productTitle"></Label>
                                <Label class="h5 caption" [text]="item.manufacturer"></Label>
                        </StackLayout>
                </GridLayout>
                <StackLayout col="1" verticalAlignment="top" (tap)="removeFromFavorites(item, i)">
                        <Image horizontalAlignment="right" src="~/images/favorite-active.png" width="20" height="20"></Image>
                </StackLayout>
            </GridLayout>
        </GridLayout>
    </ng-template>
</RadListView>

如果我要更新inner.component中的RadListView,则将其添加到“ radListView”中:

filteredItems : ObservableArray<Observable> = new ObservableArray([]);
public update(item){
    this.filteredItems.push(item)
}

但是,如果我从另一个组件添加项目,则radListView不会更新:

providers: [InnerComponent],    
constructor(private inner: InnerComponent){}
addItem(item){
    this.inner.update(item)
}

我做错了什么,为什么它没有更新?为什么从另一个组件调用函数后,我的RadListView无法更新,但是从它自己的组件中更新了?两个组件中的项目都相同。

1 个答案:

答案 0 :(得分:1)

您需要创建服务并使用example中所示的BehaviorSubject。使用providers注入组件不是常见的做法。 在您的服务中。

filteredItems;



public filteredItemsSubsSource = new BehaviorSubject(new ObservableArray<item>());
public filteredItemsSubs = this.filteredItemsSubsSource.asObservable();

addItem(item){
    this.filteredItems.push(item);
    this.filteredItemsSubsSource.next(filteredItems);
}

因此在另一个组件中注入服务并订阅

providers: [Service],    
constructor(private _service: Service){}

addItem(item){
    this._service.addItem(item);
}

this._service.filteredItemsSubs.subscribe(
            (filteredItems) => {
                this.filteredItems= filteredItems;

            }
        );