【发布时间】:2017-10-13 08:48:40
【问题描述】:
在我之前的一个问题 (dynamically create md-card from API response) 中,我根据来自 API 的大量响应动态创建卡片。
这是进行 API 调用的服务:
@Injectable()
export class WebSearchService {
private readonly _results$$ = new BehaviorSubject([]);
private readonly _isLoading$$ = new BehaviorSubject(false);
public readonly results$ = this._results$$.asObservable().shareReplay();
public readonly isLoading$ = this._isLoading$$.asObservable();
public term: string;
p: number; // page
public config = {
itemsPerPage: 10,
currentPage: this.p,
totalItems: 100
};
constructor(private http: Http){
}
search(term: string, page?: number){
return this.http.get(`my/api/{term}`).do(response => {
this._isLoading$$.next(false);
this.config.totalItems = response.json().estimated_total;
this.config.currentPage = this.p;
})
.map(response => response.json().results as WebResult[]).map(result => {
this._results$$.next(result);
this.term = term;
return result;
})
.take(1);
}
updatePage(page: number){
this.p = page;
return this.search(this.term, page);
}
}
使用服务结果的组件:
export class ResultsComponent implements OnInit {
private readonly _results$$ = new BehaviorSubject([]);
public readonly isLoading$ = this.webService.isLoading$;
public results$ = this.webService.results$;
p = 1; //
constructor(public webService: WebSearchService) { }
ngOnInit() { //
}
changePage(page: number){
console.log('Page: ' + page);
this.results$ = this.webService.updatePage(page);
}
和模板:
<ng-template [ngIf]="isLoading$ | async" [ngIfElse]="results">
is loading ...
</ng-template>
<ng-template #results>
<div class="container-fluid" *ngFor="let result of results | paginate: this.webService.config">
<!-- cards get dynamically created here -->
</div>
</ng-template>
<pagination-controls *ngIf="(results$ | async)?.length>0" maxSize="6"
previousLabel=""
nextLabel=""
align="center"
(pageChange)="changePage($event)"
class="my-pagination"
screenReaderPaginationLabel="Pagination"
screenReaderPageLabel="page"
screenReaderCurrentLabel="You are on page"
autoHide="true"
></pagination-controls>
我有另一个组件在服务中调用search 方法。但是,如果在除第 1 页之外的任何页面上调用搜索,则视图不会更新。如果我转到结果视图的第 3 页,然后执行另一次搜索,则 results$ 可观察对象会更新,但视图仍保留在旧搜索结果上。我必须在分页中手动更改到第 1 页才能获得新结果。有没有办法自动刷新视图?
我已尽力解释问题。该项目非常大,因此我无法创建 plunkr,但愿意解释/提供更多代码。
感谢任何帮助。
【问题讨论】:
-
好吧,老实说......你的代码有很多问题,我什至不会考虑像 NgZone 或 ChangeDetectorRef 这样复杂的东西 - 需要进行大量更正在那些真正成为问题之前......但我真的不明白你想要做什么。例如 - 为什么有这么多 BehaviorSubjects 可以转换为 observables?仅返回 http.get() 映射结果还不够吗?您是否正在尝试实现某种缓存?只是一个提示:您的直接问题出在 ResultsComponent.changePage() 函数中。
-
您能提供一些建议或改进吗?
-
当然可以,但我需要一些东西来开始。我看不到您要做什么,因此除非您对此有所了解,否则我将无法提出任何有意义的建议。您正在描述 what 和 how 您在做什么 - 您创建了与组件 B 对话的组件 A 等.,当我问为什么时,您以这种方式而不是另一种方式创建它们。我想了解您要解决的实际任务。
标签: angular