使用Typescript获取Angular 2中的属性 [英] Get properties in Angular 2 using Typescript

查看:52
本文介绍了使用Typescript获取Angular 2中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使属性 fullName 显示名字和姓氏.如何使get属性起作用?

I'm trying to make the property fullName display the first and the last name. How to make the get property to work?

请参见此插件.

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属性.但我根据以下答案设法弄清了这一点.谢谢!

EDIT What I actually wanted to achieve was how to use get properties when calling a service and subscribing for the result. But I managed to figure it out based on below answers. Thanks!

请参阅我更新后的插件

推荐答案

工作的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');
}

这篇关于使用Typescript获取Angular 2中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆