首页 > 解决方案 > 从模型中提取数据到变量

问题描述

我是 typescript 和 angular 的新手,我试图使用 angularfire2 从 firebase 获取一些数据,并将其分配给变量,以便稍后在其他一些函数中使用。我只熟悉 javascript 点表示法,在其中我使用点表示法访问对象的成员似乎不适用于角度,有人可以帮我从模型中提取数据到变量吗?

我仍然很难理解 Observable 和订阅。

代码

模型

export class Reacts {
  sad?: number;
  happy?: number;
  neutral?: number;
}

服务

import { Injectable } from "@angular/core";
import {
  AngularFirestore,
  AngularFirestoreCollection,
  AngularFirestoreDocument
} from "angularfire2/firestore";
import { Reacts } from "../models/reacts";
import { Observable } from "rxjs";
@Injectable({
  providedIn: "root"
})
export class ReactService {
  mapCollection: AngularFirestoreCollection<Reacts>;
  reacts: Observable<Reacts[]>;

  constructor(public afs: AngularFirestoreDocument) {
    this.reacts = this.afs.collection("reacts").valueChanges();
  }

  getItems() {
    return this.reacts;
  }
}

零件

import { Component, OnInit } from "@angular/core";
import { Reacts } from 'src/app/models/reacts';
import { ReactService } from 'src/app/services/react.service';

@Component({
  selector: "app-reacts",
  templateUrl: "./reacts.component.html",
  styleUrls: ["./reacts.component.css"]
})
export class ReactsComponent implements OnInit {


  react: Reacts[];
  happy: number;
  sad: number;
  neutral:number;


  constructor(private reactsService: ReactService ) {}

  ngOnInit(): void {
    this.reactsService.getItems().subscribe(reacts => {
      this.react = reacts;
      console.log(reacts); //this works print an array object of data from database
      this.happy= reacts.happy// what i'm trying to achieve
    });
  }

}

标签: javascriptangulartypescriptfirebase

解决方案


好的,我给你分解一下。您正在尝试访问.happy,但它实际上是一个数组React[]

  ngOnInit(): void {
    this.reactsService.getItems().subscribe((reacts:Reacts[]) => { // Note I have defined its model type
      this.react = reacts;
      console.log(reacts); //this works print an array object of data from database
      //this.happy= reacts.happy // Now VS code will show you error itself
      this.happy = reacts[0].happy; 
    });
  }

typscript 的强大之处在于它是强类型语言。如果您在服务中进行如下更改,VS Code 将自行向您解释错误:

export class ReactService {
  mapCollection: AngularFirestoreCollection<Reacts>;
  reacts: Observable<Reacts[]>;

  constructor(public afs: AngularFirestoreDocument) {
    this.reacts = this.afs.collection("reacts").valueChanges();
  }

  getItems(): Observable<Reacts[]> { // added return type
    return this.reacts;
  }
}

一旦我提供了返回类型getItems(),您甚至不必.subscribe((reacts:Reacts[])像我在您的组件中所做的那样定义类型。


推荐阅读