angular2 - 根据之前的值更新一个值

angular2 - Updating a value based on its previous value

我正在尝试创建一个博客系统,每次查看 post 时都会增加某个 post 的浏览量。我正在为数据库使用 firebase,当我去检索 post 视图的值,然后更新它时,它会不断增加值并冻结我的浏览器。下面是我的代码。有什么建议吗?

@Component({
  templateUrl: './post.html',
  styleUrls: ['./post.css']
})

export class Post {
    post: any;

    constructor(db: AngularFireDatabase, router: Router, route: ActivatedRoute){
        route.params.forEach(p => {
            let id = p['id'];
            if(id != null){
                let views = 0;
                let postRef: AngularFireObject<any> = db.object('/Posts/'+id);
                this.post = postRef.snapshotChanges().subscribe(actions => {
                    this.post = actions.payload.val();
                    let v = this.post.views + 1;
                    postRef.update({
                        views: v
                    })
                });
            }else{
                router.navigate(['/']);
            }
        });  
    }
}

这可能对您有帮助:

让视图成为全局变量,这样每次它都可以与您的@template 绑定。

public views :number = 0;

并使用它,

工作样本@https://angular-5urevo.stackblitz.io/

import { Component, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { Subscription} from 'rxjs';

export class PostComponent implements OnDestroy  {
  post: any;  
  postRef: AngularFireObject<any>;
  postRefValueSub: Subscription;
  postRefUpdateSub: Subscription;

  constructor(protected db: AngularFireDatabase, protected router: Router, protected route: ActivatedRoute) {
    if(!this.route.snapshot.params['id']) {  
      this.router.navigate(['/']);
      return;
    }

    this.postRef = db.object(`/posts/${this.route.snapshot.params['id']}`);
    /* updating post info to view ... */
    this.postRefValueSub = this.postRef.valueChanges().subscribe(value => this.post = value); 
    this.update();  
  }

  /* updating post views .... */
  update(value?: any){
    /* increment post's view and unsubscribe to prevent nested looping...  */
    this.postRefUpdateSub = this.postRefUpdateSub || this.postRef.valueChanges().subscribe((value) => {     
        this.postRefUpdateSub = this.unsubscribe(this.postRefUpdateSub);
        this.post = value || this.post || { views: 0 };
        this.post.views++;
        this.postRef.update(this.post);
    });
  }

  /* helper to unsubscribe from a subscription ...*/
  unsubscribe(subscription: Subscription) : Subscription {
    if(!subscription) { return subscription; }
    if(!subscription.closed) { subscription.unsubscribe(); } 
    return null;
  }

  /* unsubscribing from all subscriptions ... */
  ngOnDestroy(){
    this.postRefValueSub = this.unsubscribe(this.postRefValueSub);
    this.postRefUpdateSub = this.unsubscribe(this.postRefUpdateSub);
  }
}