javascript - 从模型中提取数据到变量
问题描述
我是 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
});
}
}
解决方案
好的,我给你分解一下。您正在尝试访问.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[])
像我在您的组件中所做的那样定义类型。
推荐阅读
- wordpress - 如何按某些类别显示我的所有帖子?
- html - 为什么新的自定义类优先于与先前加载的文件命名不同的类?
- jquery - 如何使用 JavaScript 函数验证字段?
- html - Flexbox - 在多列中对齐项目基线
- sql - 内部查询中的最大(日期)
- kubernetes - 在 GKE 上管理多环境 Kubernetes 应用程序?
- powershell - 在 Powershell 中使用 PSCredential 时方法调用错误
- python-3.x - 我如何从 def cal_fun() 调用变量 c
- java - 一种在 TextView 中更改文本时间的方法?
- c++ - 静态向量对字符串类成员函数