我得到了这个错误
将“允诺”类型转换为“any[]”类型可能是一个错误,因为两种类型都不足以与另一种类型重叠。如果这是有意的,将表达式转换为“未知”first.ts(2352)类型“承诺”转换为“any[]”类型可能是一个错误,因为两种类型都不足以与另一种类型重叠。如果这是有意的,首先将表达式转换为“未知”。类型“承诺”缺少以下内容
服务类
import { User } from './../models/user';
import { Injectable } from '@angular/core';
import { Global } from '../shared/global';
import { Question } from '../question';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class UserService {
constructor(private httpClient: HttpClient) { }
private apiUrl=Global.WEB_API_URL;
user:User[];
getQuestions():Observable<User[]>{
return this.httpClient.get(this.apiUrl + '/Questions/GetAllQuestions')
.map((res:Response) =><user[]>res.json());
}
}用户界面
export interface User {
id:number;
question:string;
choice:Choices[]
}
export class Choices{
ChoceId:number;
Value:string;
}发布于 2019-06-04 17:16:59
显示错误是因为res.json()返回不能转换为User[]的承诺。您应该映射它以返回可观察的或user[],或者尝试解决承诺:return res.json().then(response => ({ response }));
但是,你不需要再用新的角度来做这个了。角7
HttpClient.get()自动应用res.json()并返回Observable<HttpResponse<any>>
因此,您的服务呼叫可以如下所示:
getQuestions():Observable<User[]>{
return this.httpClient.get<User[]>(this.apiUrl + '/Questions/GetAllQuestions')
}如果需要,可以执行任何映射,但不需要res.json()。
https://stackoverflow.com/questions/56447718
复制相似问题