Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

angular - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...