angular2-基于以前的值更新值
我正在尝试创建一个博客系统,每次查看某篇文章时,该系统都会增加该文章的浏览量。我正在使用firebase作为数据库,当我检索post视图的值并进行更新时,它会不断增加值并冻结我的浏览器。。下面是我的代码。。有什么建议吗angular2-基于以前的值更新值,angular,firebase,angularfire,Angular,Firebase,Angularfire,我正在尝试创建一个博客系统,每次查看某篇文章时,该系统都会增加该文章的浏览量。我正在使用firebase作为数据库,当我检索post视图的值并进行更新时,它会不断增加值并冻结我的浏览器。。下面是我的代码。。有什么建议吗 @Component({ templateUrl: './post.html', styleUrls: ['./post.css'] }) export class Post { post: any; constructor(db: AngularFi
@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;
并使用它,工作样本@
不起作用,这是一个问题,因为更新在Watcher的范围内。你为什么要用订阅来初始化此.post,然后用操作负载来初始化?而且你的方法非常混乱。您正在侦听对象的更改,然后将其递增,这将再次触发更改事件,这将继续执行嵌套循环…您正在检查每个参数中的“id”,应将其更改为“this.route.snapshot.params['id'],除非您的第一个参数是id,否则当前代码将进入无限循环ahhh lol wow thanbsIm将很快尝试此操作!!我希望firbase订阅不会基于页面加载,…没有考虑到不断的更改。谢谢您的回答。是的。Np。我无能为力。
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);
}
}