【问题标题】:Extracting data from model to variables从模型中提取数据到变量
【发布时间】:2020-07-11 08:48:11
【问题描述】:

我是 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
    });
  }

}

【问题讨论】:

    标签: javascript angular typescript firebase


    【解决方案1】:

    好的,我会为你分解它。您正在尝试访问.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[]) 中定义类型。

    【讨论】:

    • 非常感谢先生。现在只有我明白了。它现在就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    相关资源
    最近更新 更多