我希望通过employee从employee.serves.ts文件获取员工对象到employee-info.component.ts文件,以便在HTML中查看该对象的数据。
主要问题是如何从firestore获取id的对象? (只有一个对象不是集合中的所有id对象)
employee.serves.ts文件中的doc.data()给了我想要的对象,但是如何将这些数据发送到employee-info.component.ts以便在HTML中查看它。
employee.serves.ts文件
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { Employee } from '../models/Employee';
@Injectable()
export class EmployeeService {
employeesCollection: AngularFirestoreCollection<Employee>;
empolyee: Observable<Employee>;
constructor(public afs: AngularFirestore) {
this.employeesCollection = this.afs.collection('employees');
}
getEmployee(id){
this.employeesCollection.doc(id).ref.get().then(function(doc) {
this.empolyee = doc.data();
});
return this.empolyee;
}
}
employee-info.component.ts文件
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../../services/employee.service';
import { Employee } from '../../models/Employee';
import { FlashMessagesModule } from 'angular2-flash-messages';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-employee-info',
templateUrl: './employee-info.component.html',
styleUrls: ['./employee-info.component.css']
})
export class EmployeeInfoComponent implements OnInit {
id: string;
employee : Employee;
hasSalary: boolean = false;
updateSalary: boolean = false;
constructor(private employeeServaice: EmployeeService,
private router: Router,
private activateRoute: ActivatedRoute,
private fmService: FlashMessagesModule ) {
}
ngOnInit() {
this.id = this.activateRoute.snapshot.params['id'];
this.employeeServaice.getEmployee(this.id).subscribe(employee => {
this.employee = employee;
console.log(this.employee);
});
}
}
getEmployee(id){
this.employeesCollection.doc(id).ref.get().then(function(doc) {
this.empolyee = doc.data();
});
return this.empolyee;
}
// Use Arrow function inside callback
getEmployee(id){
this.employeesCollection.doc(id).ref.get().then((doc) => {
this.empolyee = doc.data();
});
return this.empolyee;
}