使用Typescript

时间:2016-05-18 12:27:32

标签: typescript angular

我试图让属性fullName显示名字和姓氏。如何让get属性工作?

请参阅此Plunk

import { Component } from '@angular/core';

export class Person {
  id: number;
  firstName: string;
  lastName: string;
  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Component({
  selector: 'my-app',
  template:`
    <h1>{{title}}</h1>
    <p>My first name is {{person.firstName}}</p>
    <p>My last name is {{person.lastName}}</p>
    <h2>My full name is {{person.fullName}}!</h2>`
})
export class AppComponent {
  title = 'Get property issue';
  person: Person = {
    id: 1,
    firstName: 'This',
    lastName: 'That'
  };
}

修改 我实际想要实现的是如何在调用服务和订阅结果时使用get属性。但我设法根据以下答案搞清楚。谢谢!

查看我更新的plunk

2 个答案:

答案 0 :(得分:4)

Working PLUNKER

试试这个

import { Component } from '@angular/core';

export class Person {
  constructor(public id: number,public firstName: string, public lastName: string){}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Component({
  selector: 'my-app',
  template:`
    <h1>{{title}}</h1>
    <p>My first name is {{person.firstName}}</p>
    <p>My last name is {{person.lastName}}</p>
    <h2>My full name is {{person.fullName}}!</h2>
    `
})
export class AppComponent {
  title = 'Get property issue';
  person: Person = new Person( 1, 'This', 'That');
}

答案 1 :(得分:3)

您需要实例化Person类型:

constructor() {
  this.person = new  Person();
  this.person.id = 1;
  this.person.firstName = 'This';
  this.person.lastName = 'That';
}

在您的情况下,person属性符合Person类型(在结构级别),但它实际上不是Person类型的实例,因为您按字面定义了对象。这意味着您需要定义文字对象中的所有属性,并且您将无法使用fullName getter,因为它不是此对象的一部分。这是一种演员。

为方便起见,请使用以下内容:

export class Person {
  constructor(public id: number,
     public firstName: string,
     public lastName: string) {
  }

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

在这种情况下,您可以使用以下内容:

export class AppComponent {
  title = 'Get property issue';
  person: Person = new Person(1, 'This', 'That');
}