I am new to Angular. I have an issue in dependency injection when displaying a list of contacts. I have a typescript interface array in which i am passing a static array of contacts which am trying to display in html.
my service class
export class ContactService {
contacts = {
'contactsList': [
{'id': 1, 'name': 'Rajesh', 'city': 'bangalore'},
{'id': 2, 'name': 'Aarjith', 'city': 'london'},
{'id': 3, 'name': 'Anjan', 'city': 'california'},
{'id': 4, 'name': 'David', 'city': 'delhi'}
]
};
constructor(
) { }
getContacts(): Observable<Contacts> {
// send contacts to subscriber
//return of({} as Contacts);
return of(this.contacts);
}
}
model class
export interface Contacts {
contactsList: Contact[];
}
export interface Contact {
id: number;
name: string;
city: string;
}
My ContactListComponent
export class ContactListComponent implements OnInit {
contacts:Contacts[]=[];//i am getting error in this line
constructor(
private contactService: ContactService
) { }
ngOnInit() {
// get contacts from service and assign it to contacts
this.contactService.getContacts().subscribe((data) => {
this.contacts = data;//error at this line
});
}
html for displaying
<p class="title"> Contact Applications </p>
<div class="list">
<p *ngFor="let contact of contacts">
{{contact.name}}
</p>
</div>
i am getting the error at the initialization Type 'Contacts' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more. where i am missing . i have changed the initialization to Contacts=[] but not seems to be working.
contacts, wich is of type Contacts[], can't compile.contacts:Contacts;instead ofcontacts:Contacts[]=[]onContactListComponent