The type 'Promise<any>' cannot be assigned to the type 'Contact[]'

After exhausting all my resources on the internet and StackOverflow, I still couldn't find the right answer. This is my first project in Angular with MongoDB, but I keep encountering this error: "Type 'Promise' is not assignable to type 'Contact[]'." Can someone help me figure out how to solve this issue? 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;
    }

Answer №1

Your approach to the getContacts method needs some adjustments. The current implementation infers the type as

Observable<Promise<any>>
, causing issues when used in a component.

To resolve this, update your code as follows:


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

Refer to the Angular documentation on Http: Accessing typed responses

Additionally, consider converting Contact from a class to an interface or type. Here's a helpful discussion on this topic: Avoiding common pitfalls with the http client

Answer №2

It seems like you're attempting to retrieve an array of objects directly from a Promise. To achieve this, follow these steps:

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

  let usersArray : User[] = JSON.parse(js);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Observables for AngularJS Services across Multiple Components in a View

My current challenge lies in Angular, where I am struggling to implement Observables in a service that will be utilized by multiple components. The issue at hand involves having Component A and Component B nested inside Component C (in a tab style layout). ...

The type 'angular' does not have a property of this kind

Having trouble importing a method into my Angular component. An error keeps popping up: Property 'alerta' does not exist on type 'typeof PasswordResetService'. any I've double-checked the code and everything seems to be in order! ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

Navigating through Python pymongo and MongoDB to locate a specific key:value pair with the number 2

Here is my MongoDB sample data: MONGO > db.pages.findOne() { "_id" : ObjectId("519b6e81661b820d0e5d4f83"), "papers" : { "text" : "RT @sydest: Sütaş reklamlarındaki inekleri erkekler seslendirdiği sürece bu cinsiyet ayrımcılığı bitme ...

Tips for resolving the issue: "Encountered error loading module script..." in Angular 8 and Electron 5

I have been working on developing an Electron 5 app using Angular 8. Despite following numerous online tutorials, I keep encountering the same error. Initially, I set up a new project and ran ng serve --open, which successfully displayed the default angul ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

Modifications made to Angular 7 templates are not appearing in MVC 5

Currently, I am utilizing Angular 7 with MVC5 in Visual Studio 2019. However, I have encountered an issue while trying to render the Angular template in my index.cshtml file. I access the Angular template in index.cshtml using ``. The template loads perfec ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...

Reducing latency in connecting node.js with MongoDB for handling extensive datasets

While running mongoimport with csv type through my node.js app, I noticed that the results were great when operating on localhost. However, upon moving both the nodejs codebase and mongodb to a server environment (both located on the same server), the re ...

How to verify in HTML with Angular whether a variable is undefined

When it comes to the book's ISBN, there are instances where it may not be defined. In those cases, a placeholder image will be loaded. src="http://covers.openlibrary.org/b/isbn/{{book.isbn[0]}}-L.jpg?default=false" ...

Leveraging the 'ref' keyword in TypeScript with Next.js

Currently, I am learning TypeScript in React but encountered a warning. import {useref} from 'react' export default function test(){ cons tmp = useRef() const data = tmp.current?.value return ( <div> <input type = ...

The parseString method is unable to find the specified member

I have an XML file that needs to be converted to JSON for use in my application. The service returns the XML file like this: constructor(private http: HttpClient) { } loadXml() { return this.http.get('../../assets/1bbc5495-3872-4058-886e-aeee2a1cd ...

Obtain the hexadecimal color code based on the MUI palette color name

Is there a way to extract a hexcode or any color code from a palette color name in Material UI? Here is my use case: I have a customized Badge that I want to be able to modify just like the normal badges using the color property. The component code looks ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

How can I retrieve one distinct document for each group based on a shared property value in MongoDB?

I have a database collection set up in MongoDB with a schema like this: var personSchema = new mongoose.Schema({ _id: ObjectId, name: String, // ... alias: String }; (I am using mongoose, but the details are not important). Because I retrieve pe ...

Dealing with CORS policy challenge

I am encountering an issue with Access to XMLHttpRequest at 'http://demo.equalinfotech.com/Iadiva/images/product/1634623781ladiva_barbara_01.glb' from origin 'http://localhost:8100' being blocked by CORS policy due to the absence of the ...

The error message "Unable to adjust headers once they have been sent. Angular Universal ExpressJS" appears

I am trying to implement a 404 error response in my Angular 5 component with server-side rendering. In my server.js file, I have set up the following: app.engine('html', (_, options, callback) => { let engine = ngExpressEngine({ bootst ...