【发布时间】:2021-01-20 15:10:46
【问题描述】:
我有一个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}})
}
【问题讨论】:
-
如果它是一个错误或 observable 是否完成,它会停止工作吗?
-
@Elmehdi 没有错误,但是您可以看到我控制台记录了帖子,但控制台上没有出现任何内容。就像,虽然 url 发生了变化,但新的 id 没有正确传递
-
请发布您的
this.publicSrv函数的代码。getSingePost,getCommentsFromPost,getSubComments. -
@fridoo 嘿,我发布了你提到的函数的代码
标签: angular typescript routes rxjs observable