错误错误:未捕获(在承诺中):TypeError:无法设置未定义的属性“empolyee”

时间:2018-01-01 18:43:16

标签: javascript html angular google-cloud-firestore angular4-router

我想通过id从 employee.serves.ts 文件获取员工对象 employee-info.component.ts 文件,以便查看此对象的数据HTML。

主要问题是如何从firestore获取id的对象? (只有一个对象不是集合中的所有id对象)

employee.serves.ts 文件中的

doc.data()为我提供了我想要的对象,但如何将此数据发送给员工 - 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);
        });
    }
}

1 个答案:

答案 0 :(得分:0)

 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;
 }