我有一个posts.component。在 posts.component.html 中,我有以下内容
<ngx-masonry class="masonry" [options]="myOptions" [updateLayout]="hasPostOpened">
<div ngxMasonryItem class="masonryItem" *ngFor="let post of posts;index as idx" (click)="showPostDetail(post)" >
<div class="crop">{{post.description}}</div>
<img [src]="imgConstructor(post.img)">
</div>
<div ngxMasonryItem class="masonryItem masonryUser" *ngFor="let user of usersToDisplay" (click)="navigateToProfile(user.id)" >
<img [src]="userImgConstructor(user.profileImage)">
<div class="crop-user">{{user.username}}</div>
</div>
</ngx-masonry>
</div>
<div class="detail" *ngIf="hasPostOpened">
<router-outlet></router-outlet>
</div>
函数 showPostDetail(post)定义如下:
showPostDetail(post) {
this.sharedSrv.getHasPostOpened().subscribe(hasOpened => {
if(hasPostOpened)
this.router.navigate(['/post-detail/' + post.id]);
else {
this.sharedSrv.setHasPostOpened(true);
this.router.navigate(['/post-detail/' + post.id]);
}
})
}
因为我没有重新提交 post-detail.component ,所以我将帖子的ID传递给路线,并在 post-detail.component 中订阅了路线>,这样我就可以获取帖子的ID并为新帖子构建新视图:
async ngOnInit(){
this.route.paramMap.subscribe(async params => {
this.waitUntilDataLoaded = false;
this.subComments = [];
this.post = {}
let post_id = params.get('id');
await this.publicSrv.getSinglePost(post_id).toPromise().then(post => {
this.post = post;
console.log(post);
})
await this.publicSrv.getCommentsFromPost(post_id).toPromise().then(async mainComments => {
this.mainComments = mainComments;
for(let mainComment of this.mainComments){
this.subComments.push(await this.publicSrv.getSubComments(this.post.id, mainComment.commentator_id, mainComment.id).toPromise())
}})
this.waitUntilDataLoaded = true;
})
}
我可以正确地正确打开6条帖子,如果我尝试打开第七条帖子,则订阅每次都会停止工作。为什么在详细视图中打开6个帖子后订阅总是停止工作?
编辑:
getSinglePost()
getSinglePost(p_id){
return this.http.get(this.publicUrl + 'get/single-post', {params: {p_id: p_id}});
}
getSubComments()
getSubComments(p_id, commentator_id, row_id){
return this.http.get(this.publicUrl + "get/sub-comments", {params: {p_id: p_id, commentator_id: commentator_id, row_id: row_id}});
}
getCommentsFromPost()
getCommentsFromPost(p_id){
return this.http.get(this.publicUrl + "get/main-comments", {params: {p_id: p_id}})
}
答案 0 :(得分:1)
您可以像这样包装您的订阅吗?
.subscribe({
next: // your usual subscription function,
complete: () => console.log('completed')
})
如果在控制台中显示“已完成”,则表示可观察对象已完成。
我可能已经输入了一个类型,以确保它应遵循以下模板:
CHOOSE