Angular如何从service获取点赞计数器变量并在component模板展示
问题解决方法
你当前的问题是:组件中声明的postLoveIts是独立的本地变量,和PostsService中的同名变量没有建立同步关系,且PostsService中点赞数更新时没有主动通知关联组件,所以模板无法拿到最新值,按以下步骤修改即可:
第一步:修改post.service.ts,新增计数变更通知逻辑
你需要为点赞计数新增Subject用来发射变更事件,修改后完整代码如下:
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Post } from '../models/post.model'; @Injectable() export class PostsService { postLoveIts : number = 0 ; // 新增点赞计数的Subject,用于通知订阅者数值变更 postLoveItsSubject = new Subject<number>(); private posts : Post[] = [ { title: "Cuite mémorable avec mes friends", content: "lorem ipsum", } ]; postsSubject = new Subject<any[]>(); emitPosts() { this.postsSubject.next(this.posts); } // 新增发射最新点赞数的方法 emitPostLoveIts() { this.postLoveItsSubject.next(this.postLoveIts); } createNewPost(newPost : Post) { this.posts.push(newPost); this.emitPosts(); } removePost(post : Post) { const postIndexToRemove = this.posts.findIndex( (postEl) => { return postEl === post; } ); this.posts.splice(postIndexToRemove, 1); this.emitPosts(); } addOne() { this.postLoveIts = this.postLoveIts + 1; console.log("like(s) :" + this.postLoveIts); // 数值变更后通知所有订阅的组件 this.emitPostLoveIts(); } subtractOne() { this.postLoveIts = this.postLoveIts -1; console.log("like(s) :" + this.postLoveIts); // 数值变更后通知所有订阅的组件 this.emitPostLoveIts(); } }
第二步:修改post-list.component.ts,订阅点赞计数变更
你需要在组件中订阅service里的点赞计数事件,同步更新本地变量,修改后完整代码如下:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { Post } from '../models/post.model'; import { PostsService } from '../services/posts.service'; @Component({ selector: 'app-post-list', templateUrl: './post-list.component.html', styleUrls: ['./post-list.component.scss'] }) export class PostListComponent implements OnInit, OnDestroy { posts : Post[]; postsSubscription: Subscription; // 新增点赞计数的订阅对象 loveItsSubscription: Subscription; postLoveIts : number = 0 ; constructor(private postsService: PostsService, private router: Router) { } ngOnInit(): void { this.postsSubscription = this.postsService.postsSubject.subscribe( (posts: Post[]) => { this.posts = posts; } ); // 订阅点赞计数的变更事件,更新本地变量 this.loveItsSubscription = this.postsService.postLoveItsSubject.subscribe( (count: number) => { this.postLoveIts = count; } ) this.postsService.emitPosts(); // 组件初始化时主动拉取一次当前点赞数 this.postsService.emitPostLoveIts(); } onAddOne() { this.postsService.addOne(); } onSubtractOne() { this.postsService.subtractOne() } onDeletePost(post: Post) { this.postsService.removePost(post); } ngOnDestroy() { this.postsSubscription.unsubscribe(); // 组件销毁时取消点赞计数的订阅,避免内存泄漏 this.loveItsSubscription.unsubscribe(); } }
补充说明
你当前的写法是全局统一的点赞计数器,如果需求是每个帖子单独统计点赞数,只需要把loveIts字段放到Post模型中,修改service中加减计数的逻辑,传入对应post的索引修改对应值即可,现有模板不用调整。
内容的提问来源于stack exchange,提问作者user16587096
相关产品推荐
相关产品推荐

