如何在Angular中使用Observable初始化Typescript数组接口

时间:2019-07-14 10:05:33

标签: angular typescript observable

我是Angular的新手。显示联系人列表时,依赖注入中存在问题。 我有一个打字稿接口数组,我在其中传递了一个静态的联系人数组,试图以html显示。

我的服务等级

 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);
      }
    }

模型类

 export interface Contacts {
      contactsList: Contact[];
 }

 export interface Contact {
      id: number;
      name: string;
      city: string;
 }

我的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

    <p class="title"> Contact Applications </p>
    <div class="list">
      <p *ngFor="let contact of contacts">
        {{contact.name}}
      </p>
    </div>

我在初始化时遇到错误,类型'Contacts'缺少类型'any []'中的以下属性:length,pop,push,concat和另外26个。我想念的地方。我已将初始化更改为Contacts = [],但似乎无法正常工作。

3 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

export interface Contact {
  id: number;
  name: string;
  city: string;
}

export class ContactService {

  constructor() { }

  contacts: Contact[] = [
    { 'id': 1, 'name': 'Rajesh', 'city': 'bangalore' },
    { 'id': 2, 'name': 'Aarjith', 'city': 'london' },
    { 'id': 3, 'name': 'Anjan', 'city': 'california' },
    { 'id': 4, 'name': 'David', 'city': 'delhi' }
  ];

  getContacts(): Observable<Contact[]> {
    return of(this.contacts);
  }
}

export class ContactListComponent implements OnInit {

  constructor(
    private contactService: ContactService
  ) { }

  contacts: Contact[] = [];

  ngOnInit() {
    this.contactService.getContacts().subscribe((contacts) => {
      this.contacts = <Contact[]>contacts;
    });
  }
}

答案 1 :(得分:1)

您的代码中有一些错误。应该是这样的:

export interface Contacts {
  contactsList: Contact[];
}

export interface Contact {
  id: number;
  name: string;
  city: string;
}

@Injectable({providedIn: 'root'})
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' }
    ]
  };

  getContacts(): Observable<Contacts> {
    return of(this.contacts);
  }
}


export class ContactListComponent implements OnInit {
  contacts: Contact[]; // <= This is the correct type
  constructor(private contactService: ContactService) {}

  ngOnInit() {
    this.contactService.getContacts().subscribe((data: Contacts) => {
      // You need to get the contatactsList from the service answer.
      this.contacts = data ? data.contactsList : [];
    });
  }
}

请参见this demo

答案 2 :(得分:0)

您尚未使用定义一个“数组接口”

export interface Contacts {
  contactsList: Contact[];
}

您宁可使用数组类型属性定义类型。表达式[]产生一个Array值。

因此,声明

let contacts: Contacts = [];

格式错误,因为数组没有contactList属性。

正确的代码将显示为

let contacts: Contacts = {
  contactList: []
};