我正在尝试使属性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
解决方法
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'); }