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

时间:2021-03-17 20:52:52

标签: angular mongodb typescript angular-promise

我已经尝试了互联网上的所有内容,但在 stackoverflow 上我找不到正确的答案。这是我与 mongodb 一起在 angular 中的第一个项目。但我收到此错误“类型 '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;
    }

2 个答案:

答案 0 :(得分:2)

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

将您的代码更改为:


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

阅读关于 Http 的 Angular 手册:Requesting a typed response

此外,将 Contact 从类更改为接口或类型。见common pitfall when using http client

答案 1 :(得分:0)

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

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

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