Javascript 如何在加载时更新可观测阵列
我试图在点击load more后更新Observable数组,但这会导致对API的多次调用 这是我的html:Javascript 如何在加载时更新可观测阵列,javascript,angular,rxjs,observable,Javascript,Angular,Rxjs,Observable,我试图在点击load more后更新Observable数组,但这会导致对API的多次调用 这是我的html: <app-productlistother *ngFor="let item of favs$ | async" [item]="item"></app-productlistother> <a (click)="loadMore()">Load More</a> 和服务: getFavorites(page): Observabl
<app-productlistother *ngFor="let item of favs$ | async" [item]="item"></app-productlistother>
<a (click)="loadMore()">Load More</a>
和服务:
getFavorites(page): Observable<Response> {
return this._http.get(environment.baseUrl + 'favorite?page=' + page)
.map((result: Response) => result.json().data);
}
我怎样才能解决这个问题?在每个新的getFavoritespage请求中,我需要在数组底部推送新结果
@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...
}
现在,根据您需要对该值执行的操作,您可能需要在组件中执行更改以进行更新,但这是使用可观察值的要点
另一种选择是在模板中使用异步管道,而不是在构造函数中显式订阅流。同样,这取决于您需要对bool值做什么。所以您没有HTML,而模板只是{{item.name}}?在这种情况下,为什么不这样构造它:
<ng-template *ngFor="let item of favs$ | async">
<app-productlistother [item]="item"></app-productlistother>
</ng-template>
这使异步管道远离重复元素,因此异步管道不会在项目的每次迭代中重复。我认为这就是为什么它被多次调用的原因,很可能与您拥有的项目数相同
此外,如果合并不起作用,请尝试concat。Concat将等待第一个可见光发射完成,然后加入第二个可见光。合并不会等待第一个可观察对象完成。我想,如果您单击“加载更多”,而不是将初始数据与第二批数据交织在一起,您会希望数据按顺序加载,以此类推 您的服务中需要一个observable,需要订阅组件中的observable,一旦触发再次加载,数据将添加到observable,组件将列出任何更改,然后更新它自己。您能给我举个例子吗?@Vladmir举个例子,希望它能帮助查看您的HTML,您正在重复并将一个新项作为输入传递给子组件。HTML是什么样子的?我有一种感觉,你正在异步每个项目,而不是异步一次并重复异步的项目。在我只是这样显示{{item.name}我不需要订阅可观察的异步管道为我做这件事我只需要添加新的可观察的到当前。我不明白我没有在我的代码中使用订阅,异步管道为我做这件事。。。我需要在加载更多函数后将2个可观测值合并为1,然后在示例中不使用可观测值,您可以将其与模板中的异步管道一起使用,更新了答案
@Component({...})
export class MyComponent {
currentBool: any;
constructor(service: MyBooleanService) {
service.myBool$.subscribe((newBool: any) => { this.currentBool = newBool; });
}
}
<ng-template *ngFor="let item of favs$ | async">
<app-productlistother [item]="item"></app-productlistother>
</ng-template>