为什么在angular2项目中访问typescript对象的属性时返回undefined?

时间:2017-06-25 08:05:59

标签: angular typescript

我有一个angular2项目,我在其中使用http模块发出get请求。从服务器检索对象,并且显然正确地反序列化为相应的typescript对象,但是当我尝试访问属性时,它返回undefined,即使在我尝试访问这些属性之前将对象打印到控制台时,数据也是如此似乎存在。

这就是我的get请求方法。

  getDataForEmployee(data){
    var url = this.active+"/guest/"+data;

    var headers = new Headers();

    headers.append("Content-Type", "application/json");

    return this.http
      .get(url, {headers:headers})
      .toPromise()
      .then((res:Response)=> res.json() as Employee);

  }

这是该方法处理响应的方式。

this.employeeHttp.getDataForEmployee(userid)
  .then((employee:Employee)=>{
    console.log(employee);
    console.log("firstname: "+employee.firstName);
    ...

Employee类如下所示:

 export class Employee {

    ...
      private _firstName:string;
    ...

      get firstName(): string {
        return this._firstName;
      }

      set firstName(value: string) {
        this._firstName = value;
      }

    ...
    }

图像显示发出此请求时的控制台输出。 Image of the console output

我不明白为什么当我尝试检索firstName时它返回undefined,即使它刚好存在于之前的对象中。

关于为什么会发生这种情况的任何想法对我都非常有帮助。

1 个答案:

答案 0 :(得分:3)

您期望的只能通过继承来实现。但是将对象类型声明为类并不会使对象继承该类,即employee不是代码中Employee的子代。

要调用getter,您必须首先继承它,例如:

let emp = new Employee("Dan"); // passing only firstName for demo

然后您就可以访问emp.firstName,它将返回Dan。您还需要接受Employee课程中的参数。

我做了一个plnkr演示,其中Employee类接受firstName的一个参数。保持开发人员工具处于打开状态,以便在getter和setter中都停止。

由于typescript只检查编译类型的代码,因此无法检查API是否在运行时返回了其他内容,例如:_name而不是_firstName。因此,我建议您使用interface代替class