2016-11-10 25 views
1

我有一個組件這樣的數據:如何在Angular 2中使用另一個組件的屬性值?

@Injectable() 
export class ContactsData { 

    public CONTACTS: Contact[] = [ 
     { id: "1", firstname: "Maxxx", lastname: "Smith", email: "[email protected]" }, 
     { id: "2", firstname: "Chris", lastname: "Raches", email: "[email protected]" }, 
     { id: "3", firstname: "Michael", lastname: "Alloy", email: "[email protected]" }, 
     { id: "4", firstname: "John", lastname: "Doe", email: "[email protected]" }, 
     { id: "5", firstname: "Jenny", lastname: "Doe", email: "[email protected]" } 
    ]; 

我試圖從另一個服務訪問它,但我得到「無法找到名爲‘聯繫’」:

import {ContactsData} from "./data"; 
import {Contact} from "./contact"; 

@Injectable() 
export class ContactService{ 
    getContacts(){ 
     return Promise.resolve(ContactsData.CONTACTS); // Error here 
    } 

我已經顯然跳過了我不明白的一個步驟 - 請指向正確的方向...

回答

1

您需要在ContactService中注入ContactsData。

@Injectable() 
export class ContactService { 
    constructor(private data: ContactsData) {} 

    getContacts() { 
    return Promise.resolve(this.data.CONTACTS); 
    } 
} 
+0

謝謝,但現在我得到:'的ReferenceError:聯繫不defined.' –

+0

做工精細這裏:http://plnkr.co/edit/aXlzW9T1qzGdchmnvHwz?p=preview。如果您想獲得更多幫助,請發佈一個解決問題的方案。 –

相關問題