首页 文章

Ionic - 通知页面变量已更改的最佳方法是什么

提问于
浏览
1

假设我们有一个显示项目列表的页面 ListItemPage

  • 在ts文件中,我们有一个变量 items: any = [];

  • 在html文件中,我们有 <ion-item *ngFor="let item of items">

用户可以单击()按钮以推送另一个页面 AddItemPage ,他将在该页面上创建新项目 . 单击“保存”时,新项目将保存在数据库中(通过服务),并弹出页面 .

通知 ListItemPage 应该更新其 items 变量的最佳/通常方法是什么?

2 回答

  • 1

    通知ListItemPage应该更新其items变量的最佳/通常方法是什么?我应该使用活动吗? https://ionicframework.com/docs/api/util/Events/我应该使用Observable吗?

    好吧,如果您已经拥有与项目相关的服务(可能是从后端获取项目的服务),最好使用Observables以保持一致 .

    @Injectable()
    export class YourItemsService {
    
        public onItemsChange: Subject<any> = new Subject<any>();
    
        // ...
    
        public changeItems(someParam: any): void {
            // ...
    
            // Send the new data to the subscribers
            this.onItemsChange.next(newItems);
        }
    
    }
    

    这样,每个页面都可以订阅它并在数据更改时进行更新,并且可以使用相同的服务来更改数据,因为知道更改也将传播到订阅它的所有页面:

    @Component({
        selector: 'another-page',
        templateUrl: 'another-page.html'
    })
    export class AnotherPagePage {
    
        constructor(private yourItemsService: YourItemsService) {}
    
        updateItems(data: any) { 
            // Use the service to modify the data, keeping everyone updated
            this.yourItemsService.changeItems(data);
        }
    
    }
    

    和...

    @Component({
        selector: 'some-page',
        templateUrl: 'some-page.html'
    })
    export class SomePagePage {
    
        private itemsChangeSubscription: Subscription;
    
        constructor(private yourItemsService: YourItemsService) {
            // Subscribe to changes in the items
            this.itemsChangeSubscription = this.yourItemsService.onItemsChange.subscribe(data => {
                // Update the data of the page...
                // ...
            });
        }
    
        ionViewWillUnload() {
            // Clear the itemsChangeSubscription
            this.itemsChangeSubscription && this.itemsChangeSubscription.unsubscribe();
        }
    }
    

    为什么这样做?如果您需要在每次修改项目时执行某些逻辑(例如更新其他服务或任何其他属性中的总金额),您可以在服务中执行此操作,从而将该逻辑集中在一个位置 . So each page should worry about how to handle the new data to update its current state, but any other change will be handled by the service


    如果由于某种原因你没有集中服务,只为一个事件创建一个新的并不是一个好主意,你可以使用 Ionic's Events .

    如果执行此操作并且每次发布事件时都需要执行一些自定义逻辑,则需要在订阅每个事件的每个页面上重复该代码 .

    Additional details about the Ionic's events

    如果你看一下Ionic事件的实现( source code ),你会发现内部Ionic不使用Observables,而是一个存储回调的数组,以便在事件发布时执行

  • 2

    这是一个艰难的 . 这似乎是一个“有赖”的问题所以如果没有详细描述你的需求,恐怕不可能回答什么是最好的 .

    所以这是 another way 来更新 items .

    使用数据获取逻辑(more about navigating-lifecycle-events)实现 ionViewWillEnter() 方法 .

    每次要显示页面时,此方法都会触发,例如当它即将变得活跃时 . 所以通过实现它是这样的:

    ionViewWillEnter() {
        this.dataService.getItems()
            .then(result => {
                this.items = result;
            })
            .catch(err => {
                console.log(err);
            });
        });
    }
    

    并在你的 dataService

    let _items = [];
    
    public getItems() {
        return new Promise ((resolve, reject) => { 
            if(!this._items || this._items.lenght == 0) {
                // this._items = Read items from DB / web service ...
            }
    
            resolve(this._items);
        });
    }
    
    public addItem(item: any) {
        this._items.push(item);
        // update db..
    }
    

    每次显示页面时都会有新数据 .

    通过调用 addItem 方法更新数据时,请确保对 getItems 方法的所有后续调用都获取新数据 . 您还可以说数据已缓存,因此没有不必要的数据库查询 .

相关问题