Daniel Minnaar
Daniel Minnaar

Reputation: 6295

How do I consume another component's property value in Angular 2?

I have this data in a component:

@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]" }
    ];

I'm trying to access it from another service, but I get "Cannot find name 'CONTACTS'":

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

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

I've obviously skipped a step I don't understand - please point me in the right direction...

Upvotes: 1

Views: 31

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

You need to inject ContactsData in ContactService.

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

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

Upvotes: 1

Related Questions