使用 Typescript 在 Angular 2 中获取属性

Mag*_*röm 5 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'
  };
}
Run Code Online (Sandbox Code Playgroud)

编辑 我真正想要实现的是如何在调用服务和订阅结果时使用获取属性。但我设法根据以下答案弄清楚了。谢谢!

查看我更新的plunk

Ank*_*ngh 8

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');
}
Run Code Online (Sandbox Code Playgroud)