【问题标题】:Get properties in Angular 2 using Typescript使用 Typescript 在 Angular 2 中获取属性
【发布时间】:2016-05-18 12:27:32
【问题描述】:

我正在尝试使属性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

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你需要实例化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');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-19
        • 2019-04-08
        • 1970-01-01
        • 2017-06-26
        • 2018-06-13
        • 2018-12-14
        相关资源
        最近更新 更多