【问题标题】:How to update observable array on load more如何在加载更多时更新可观察数组
【发布时间】:2017-06-01 15:55:52
【问题描述】:

单击加载更多后,我正在尝试更新 Observable 数组,但这会导致对 API 的多次调用。

这是我的html:

<app-productlistother *ngFor="let item  of favs$ | async" [item]="item"></app-productlistother>

<a (click)="loadMore()">Load More</a>

组件:

ngOnInit() {
    this.favs$ = this._favoriteService.getFavorites(this.pageNum);
  }

  private loadMore() {
    this.pageNum = this.pageNum + 1;

    this.favs$ = this.favs$.merge(this._favoriteService.getFavorites(this.pageNum));
  }

和服务:

getFavorites(page): Observable<Response> {
    return this._http.get(environment.baseUrl + 'favorite?page=' + page)
      .map((result: Response) => result.json().data);
  }

我该如何解决这个问题?在对getFavorites(page) 的每个新请求中,我需要将新结果推送到数组底部...

【问题讨论】:

  • 您需要在您的服务中使用 observable,并且需要订阅组件中的 observable,一旦触发加载更多,数据将被添加到 observable,并且组件将列出任何更改,然后更新自己
  • 你能给我举个例子吗?
  • @Vladmir 举了一个例子希望对你有帮助
  • 查看您的 HTML,您正在重复 并将新项目作为输入传递给子组件。 HTML 是什么样的?我有一种感觉,你正在异步每个项目,而不是异步一次并重复异步的项目。
  • &lt;app-productlistother&gt;我只是这样显示{{item.name}}

标签: javascript angular rxjs observable


【解决方案1】:

所以你没有 HTML 和 &lt;app-productionother&gt; 模板只是 {{item.name}} ?在那种情况下,为什么不这样构造它:

<ng-template *ngFor="let item of favs$ | async"> 
    <app-productlistother [item]="item"></app-productlistother> 
</ng-template> 

这使异步管道远离重复元素,因此异步管道不会在项目的每次迭代中重复。我认为这就是为什么它被多次调用(可能与您拥有的项目相同的数量)。

另外,如果merge 不起作用,请尝试concatConcat 将等到第一个 observable 完成发射,然后加入第二个 observable。合并不会等待第一个 observable 完成。我想如果您单击加载更多并且没有与第二批交织的初始数据等,您希望您的数据按顺序加载。

【讨论】:

    【解决方案2】:
    @Injectable()
    export class MyBooleanService {
        myBool$: Observable<any>;
    
        private boolSubject: Subject<any>;
    
        constructor() {
            this.boolSubject = new Subject<any>();
            this.myBool$ = this.boolSubject.asObservable();
        }
    
        ...some code that emits new values using this.boolSubject...
    }
    

    然后在你的组件中你会有这样的东西:

    @Component({...})
    export class MyComponent {
        currentBool: any;
    
        constructor(service: MyBooleanService) {
            service.myBool$.subscribe((newBool: any) => { this.currentBool = newBool; });
        }
    }
    

    现在,根据您需要对该值执行的操作,您可能需要在组件中进行更改以进行更新,但这是使用 observable 的要点

    另一种选择是在模板中使用异步管道,而不是在构造函数中显式订阅流。不过,这又取决于您需要对 bool 值做什么。

    【讨论】:

    • 我不需要订阅 Observable 异步管道,我只需要向当前添加新的 observable 即可。
    • 我没找到你
    • 我不在我的代码中使用订阅,异步管道为我做......我需要在加载更多函数后将 2 个 observables 合并到 1 个
    • 那么不要在示例中使用 observable 你可以在模板中将它与异步管道一起使用,更新答案
    猜你喜欢
    • 2016-11-26
    • 2013-12-16
    • 2016-12-26
    • 1970-01-01
    • 2016-11-12
    • 2016-03-13
    • 1970-01-01
    • 2015-05-31
    • 2013-05-01
    相关资源
    最近更新 更多