我是 typescript 和 Angular 新手,我试图使用 angularfire2 从 firebase 获取一些数据,并将其分配给变量以便稍后在其他一些函数中使用。我只熟悉 javascript 点表示法,我使用点表示法访问对象的成员似乎不适用于 Angular 有人可以帮助我从模型中提取数据到变量吗
我仍然很难理解 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;
});
}
typescript 的力量来自于它是强类型语言。如果您在服务中进行如下更改,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[])
中定义类型你的组件。
关于javascript - 将数据从模型提取到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60939781/