[英]Get properties in Angular 2 using Typescript
I'm trying to make the property fullName
display the first and the last name. 我正在尝试使属性fullName
显示第一个和最后一个名称。 How to make the get property to work? 如何让get属性工作?
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'
};
}
EDIT What I actually wanted to achieve was how to use get properties when calling a service and subscribing for the result. 编辑我真正想要实现的是如何在调用服务和订阅结果时使用get属性。 But I managed to figure it out based on below answers. 但我设法根据以下答案搞清楚。 Thanks! 谢谢!
Try this 试试这个
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');
}
You need to instantiate the Person
type: 您需要实例化Person
类型:
constructor() {
this.person = new Person();
this.person.id = 1;
this.person.firstName = 'This';
this.person.lastName = 'That';
}
In your case, the person
property conforms to the Person
type (at the structure level) but it's not actually an instance of the Person
type since you define the object literally. 在您的情况下, person
属性符合Person
类型(在结构级别),但它实际上不是Person
类型的实例,因为您按字面意思定义了对象。 This means that you need to define all the properties in your literal object and you won't be able to use the fullName
getter since it's not part of this object. 这意味着您需要定义文字对象中的所有属性,并且您将无法使用fullName
getter,因为它不是此对象的一部分。 It's a kind of cast. 这是一种演员阵容。
Use the following for convenience: 使用以下方便:
export class Person {
constructor(public id: number,
public firstName: string,
public lastName: string) {
}
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
In this case, you can use the following: 在这种情况下,您可以使用以下内容:
export class AppComponent {
title = 'Get property issue';
person: Person = new Person(1, 'This', 'That');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.