2017-06-01 98 views
0

我试图在点击加载更多后更新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)我需要在阵列的底部推新结果...

+0

您需要在您的服务中使用observable,并且需要订阅组件中的obeservable,并且一旦加载更多的数据就会被触发,数据将被添加到observable中,并且组件将会列出所有更改,然后自行更新 –

+0

您能给我举个例子吗? – Vladimir

+0

@Vladmir举了一个例子,希望它有帮助 –

回答

0
@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; }); 
    } 
} 

现在取决于你需要什么要做到这一点,你可能需要在你的组件中进行更新,但这是使用可观察的要点

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

+0

我不需要订阅Observable异步管道为我做我只需要添加新的可观察到当前。 – Vladimir

+0

我没有得到你 –

+0

我没有在我的代码中使用订阅,异步管道为我做...我需要在加载更多的功能合并2观察到1 – Vladimir

0

所以你有没有HTML和<app-productionother>模板只是{{item.name}}?在这种情况下,为什么不构建这样的:

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

这保持异步管关闭的重复元件,以便不被关于项目的每个迭代重复异步管。我想这就是为什么它被称为多次(可能与你有物品相同的数字)。

此外,如果merge没有解决问题,请尝试concatConcat将等待,直到第一个可观测数据完成发射,然后将加入第二个可观测数据。合并不等待第一个观察结束。我想如果你点击加载更多,并且没有与第二批交互的初始数据等,你会希望按顺序加载数据。