如何在Angular 2中使用其他组件的属性值?

时间:2016-11-10 17:41:28

标签: angularjs

我在组件中有这些数据:

@Injectable()
export class ContactsData {

    public CONTACTS: Contact[] = [
        { id: "1", firstname: "Maxxx", lastname: "Smith", email: "max@gmail.com" },
        { id: "2", firstname: "Chris", lastname: "Raches", email: "chris@gmail.com" },
        { id: "3", firstname: "Michael", lastname: "Alloy", email: "michael@gmail.com" },
        { id: "4", firstname: "John", lastname: "Doe", email: "john@gmail.com" },
        { id: "5", firstname: "Jenny", lastname: "Doe", email: "jenny@gmail.com" }
    ];

我试图从其他服务访问它,但我得到了#34;无法找到姓名'联系人'":

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

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

我显然已经跳过了一个我不明白的步骤 - 请指出我正确的方向......

1 个答案:

答案 0 :(得分:1)

您需要在ContactService中注入ContactsData。

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

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