Angular5-类中新创建的对象返回未定义

时间:2018-10-02 18:48:26

标签: javascript typescript angular5

我有一个服务类,其中我正在传递组件中的对象,并暂时将其保存为模型类。我想从讲师(模型)中获得讲师.service.ts中的$ key。

lecturer.component.ts

onItemClick(lec: Lecturer) {
  this.lecturerService.selectedLecturer = Object.assign({},lec); // this is working properly as i have seen in console.log(lec)
}

lecturer.ts

export class Lecturer {
    $key: string;
    userName: string;
    userEmail: string;
    userProfileImageUrl: string;
}

现在我只想从service.class中的讲课中获得$ key,但是不知何故我无法获得在此函数中使用的键。

lecture.service.ts

 import { Injectable } from '@angular/core';
 import { Lecturer } from './lecturer';
 import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';

 @Injectable({
    providedIn: 'root'
 })

  export class LecturerService {
     lecturerList: AngularFireList<any>;
     assignedCourseList: AngularFireList<any>;

     selectedLecturer: Lecturer = new Lecturer();

     constructor(private db: AngularFireDatabase) {}

     getAssignedCourse() {
     this.assignedCourseList = this.db.list('Users/' + this.selectedLecturer.$key + '/Course'); //this is where i'm having problem to get the $key
       console.log(this.selectedLecturer.$key);
       return this.assignedCourseList;
     }
  }

我该怎么做才能做到这一点?

1 个答案:

答案 0 :(得分:1)

解决方案1:

我认为您应该像这样将默认值传递给它...

lecturer.ts文件

export class Lecturer {
   $key: string = '';
   userName: string = '';
   userEmail: string = '';
   userProfileImageUrl: string = '';
}

创建新对象

selectedLecturer: Lecturer = new Lecturer();

console.log(selectedLecturer)
// output will be
 { $key: '',
   userName: '',
   userEmail:'',
   userProfileImageUrl:''
 }

解决方案2:

lecture.ts文件

或添加一个构造函数以在创建新对象时分配值...

export class Lecturer {
   $key: string;
   userName: string;
   userEmail: string;
   userProfileImageUrl: string;
   constructor(key:string,userName: string,userEmail: string, userProfileImageUrl: string){
         this.$key = key;
         this.userName = userName;
         this.userEmail = userEmail;
         this.userProfileImageUrl = userProfileImageUrl
        }
}

创建新对象

selectedLecturer: Lecturer = new Lecturer('my_key','name','email','url');

console.log(selectedLecturer)
// output will be
 { $key: 'my_key',
   userName: 'name',
   userEmail:'email',
   userProfileImageUrl:'url'
 }