错误TypeError:无法在角度5中读取null的属性“singlePost”

问题描述 投票:1回答:1

使用一次方法正确地从firebase数据库中获取数据。但是使用on方法,它显示错误ERROR TypeError:无法读取null的属性'singlePost'。如何在firebase数据库的方法上使用并绑定数据?我在{this.singlePost.content = snapshot.val();}得到错误,说无法读取null的singlePost.content的值。

export class BlogDetailComponent implements OnInit {

  singlePost: Blog;
  id: any;

  constructor(private route: ActivatedRoute, private router: Router) {

    let contentUpdated: any;
  }

  ngOnInit() {
    let postId = this.route.snapshot.params['id'];
    this.getSingle(postId);
    this.id = postId;
    let starCountRef = firebase.database().ref('blogPosts/' + this.id + '/content');
    starCountRef.on('value', function (snapshot) {
      if (snapshot.val() != null) {
        this.singlePost.content = snapshot.val();
      }
    });
  }

  getSingle(id: string) {
    let dbRef = firebase.database().ref('blogPosts');
    dbRef.orderByChild('id')
      .equalTo(id)
      .once('value')
      .then((snapshot) => {
        let tmp = snapshot.val();
        let transform = Object.keys(tmp).map(key => tmp[key]);
        let title = transform[0].title;
        let content = transform[0].content;
        let imgTitle = transform[0].imgTitle;
        let img = transform[0].img;
        this.singlePost = new Blog(title, content, imgTitle, img);
      });
  };
}

如果我运行以下代码,则有效。

export class BlogDetailComponent implements OnInit{

    singlePost : Blog;
    id : any;


    constructor(private route : ActivatedRoute, private router : Router) {

      let contentUpdated : any;
    }

    ngOnInit() {
      let postId = this.route.snapshot.params['id'];
      this.getSingle(postId);
      this.id = postId;
      let starCountRef = firebase.database().ref('blogPosts/'+this.id+'/content');
      starCountRef.on('value',function(snapshot){
        if(snapshot.val() != null )
        { console.log(snapshot.val());}
      });

    }

    getSingle(id : string){
      let dbRef = firebase.database().ref('blogPosts');
      dbRef.orderByChild('id')
      .equalTo(id)
      .once('value')
      .then((snapshot) => {
        let tmp = snapshot.val();
        let transform = Object.keys(tmp).map(key => tmp[key]);
        let title = transform[0].title;
        let content = transform[0].content;
        let imgTitle = transform[0].imgTitle;
        let img = transform[0].img;
        this.singlePost = new Blog(title,content,imgTitle,img);
      });
    };
  }
javascript angular typescript firebase
1个回答
1
投票

您应该使用Arrow function / Lamba来获取回调函数中正确的this(上下文)

starCountRef.on('value',(snapshot: any) => {
    if(snapshot.val() != null ) { 
      this.singlePost = {content : snapshot.val() };
    };
});
© www.soinside.com 2019 - 2024. All rights reserved.