2016-05-18 4 views
2

プロパティfullNameに姓と姓を表示しようとしています。 getプロパティを動作させるには?角型2のプロパティをTypescriptで取得する

この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' 
    }; 
} 

EDIT は、サービスを呼び出し、結果の加入時にプロパティを取得使用する方法でした。しかし、私はそれ以下の答えに基づいてそれを把握することができました。ありがとう!

あなたはPersonタイプインスタンス化する必要があり、私の更新plunk

答えて

2

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'); 
} 
をお試しください
3

参照してください:あなたのケースでは

constructor() { 
    this.person = new Person(); 
    this.person.id = 1; 
    this.person.firstName = 'This'; 
    this.person.lastName = 'That'; 
} 

を、personプロパティは、(構造レベルで)Personタイプに準拠していますが、実際には、ANはありませんオブジェクトは文字通り定義するので、Personタイプのインスタンスです。これは、リテラルオブジェクトのすべてのプロパティを定義する必要があることを意味し、このオブジェクトの一部ではないため、fullNameゲッターを使用することはできません。それは一種のキャストです。

便宜のために、次を使用します。この場合、

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'); 
} 
関連する問題