'Promise<any>' 不可分配给类型 'Contact[]'

'Promise<any>' is not assignable to type 'Contact[]'

我已经在互联网上尝试了一切,在 Whosebug 上我找不到正确的答案。这是我在 angular 和 mongodb 中的第一个项目。但我收到此错误“类型 'Promise' 不可分配给类型 'Contact[]'。”你能看看我如何解决这个问题吗? contact.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import {map} from 'rxjs/operators';

    @Injectable()
    export class ContactService {

      constructor(private http: HttpClient) { }

      getContacts()
      {
        return this.http.get('http://localhost:3000/api/contacts')
        .pipe(map((res: Response) => res.json()));
      }

      addContact(newContact)
      {
        var headers = new HttpHeaders();
        headers.append('Content-Type', 'application/json');
        return this.http.post('http://localhost:3000/api/contact', newContact, {headers:headers})
        .pipe(map((res: Response) => res.json()));
      }
      deleteContacts(id)
      {
        return this.http.delete('http://localhost:3000/api/contact'+id)
        .pipe(map((res: Response) => res.json()));
      }
    }

contacts.component.ts

    import { Component, OnInit } from '@angular/core';
    import {ContactService} from '../contact.service';
    import {Contact} from '../contact';


    @Component({
      selector: 'app-contacts',
      templateUrl: './contacts.component.html',
      styleUrls: ['./contacts.component.css'],
      providers: [ContactService]
    })
    export class ContactsComponent implements OnInit {

      contact:Contact;
      contacts:Contact[];
      first_name:string;
      last_name:string;
      phone:string;
      constructor(private contactService: ContactService) { 
        var contacts;
      }

      
      ngOnInit() {
        this.contactService.getContacts()
          .subscribe(contacts =>
            this.contacts = contacts);
      }

    }
        

contact.ts

    export class Contact{
        _id: string;
        first_name: string;
        last_name: string;
        phone:string;
    }

可能您正在尝试直接从 Promise 获取对象数组。你必须这样做:

response.json().then(data => {

  let contacts : Contact[] = JSON.parse(js);
});

您的 getContacts 方法实现不正确。 您的实现的推断类型是 Observable<Promise<any>>,这会导致使用该方法的组件出现问题。

将您的代码更改为:


getContacts(): Observable<Contact[]> {
  return this.http.get<Contact[]>('http://localhost:3000/api/contacts');
}

阅读 Angular HTTP 手册:Requesting a typed response

此外,将联系人从 class 更改为接口或类型。参见