angular2 - 根据以前的值更新值

时间:2017-11-02 15:11:23

标签: angular firebase angularfire

我正在尝试创建一个博客系统,该系统会在每次查看帖子时增加某个帖子的观看量。我正在使用firebase作为数据库,当我去检索帖子视图的值,然后更新它,它不断增加值并冻结我的浏览器..下面是我的代码..任何建议?< / p>

@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(['/']);
            }
        });  
    }
}

2 个答案:

答案 0 :(得分:1)

工作样本@ 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);
  }
}

答案 1 :(得分:0)

这可能对您有所帮助:

让视图变量为全局变量,以便每次它都可以与@template绑定。

public views :number = 0;

并使用它,