Jeb50
Jeb50

Reputation: 7057

Type 'Observable<Promise<any>>' is not assignable to type 'Observable<myRec[]>'. Type 'Promise<any>' is missing

So I'm intending to let NG to deal with subscription during the lifecycle of a component, let it auto-subscribe/unsubscribe.

Here is my service providing observable for calls to endpoint outside, MySvc.ts

import { Injectable  } from '@angular/core';
import { HttpClient, HttpRequest, HttpHeaders, HttpErrorResponse } from "@angular/common/http";
import { Observable, throwError } from 'rxjs';
const url = '...';
@Injectable()
export class MySvc{
constructor(private http: HttpClient) { } 
getAllRec()
{
  return this.http.get(url).pipe(map((res: Response) => res.json()));
}

myRec.ts

export interface myRec
{
  name: string;
}

My display component MyPage.ts

import { Component, OnInit } from '@angular/core';
import { MySvc } from '..MySvc.service';
import { Observable, of} from "rxjs";
import { myRec} from '../models/myRec';     
@Component({...})
export class MyPage implements OnInit {
  public allRec$: Observable<myRec[]>;
constructor(private MySvc: MySvc) {}
ngOnInit()
{
  this.allRec$ = this.MySvc.getAllRec(); // see compiling error below
}

Type 'Observable<Promise>' is not assignable to type 'Observable<myRec[]>'. Type 'Promise' is missing the following properties from type 'myRec[]': length, pop, push, concat, and 26 more

Upvotes: 1

Views: 2880

Answers (2)

Dario Piotrowicz
Dario Piotrowicz

Reputation: 1102

The issue is that you're calling .json in the reponse which as you can see here: https://developer.mozilla.org/en-US/docs/Web/API/Response returns a promise

Angular already parses the response for you, so you don't need do to that, so just remove the map from the getAllRec function and also parametrize the function so that angular knows that the response contains an array of myRec like:

getAllRec()
{
  return this.http.get<myRec[]>(url);
}

You can see here that this does not give you a parsing error:
https://stackblitz.com/edit/angular-ivy-vhrk6d?file=src/app/app.module.ts

Naturally I don't have your url so I cannot test the method itself but I think this should be good enough :)

Upvotes: 4

Andrei
Andrei

Reputation: 12036

change

getAllRec()
{
  return this.http.get(url).pipe(map((res: Response) => res.json()));
}

to

getAllRec()
{
  return this.http.get<myRec[]>(url);
}

your type was wrong;

Upvotes: 2

Related Questions