我已经尝试了在堆栈上发布的所有其他解决方案,参考错误 TS2322
,但未能找到有效的解决方案 .
Error produced
ERROR in src/app/service/user.service.ts(21,9): error TS2322: Type 'Observable<{} | User>' is not assignable to type 'Observable<User>'.
Type '{} | User' is not assignable to type 'User'.
Type '{}' is not assignable to type 'User'.
Property 'id' is missing in type '{}'.
user.service
import { Injectable } from '@angular/core';
import { BaseService } from './base.service';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { User } from '../model/user';
import { MessageService } from './message.service';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UserService extends BaseService {
constructor(
http: HttpClient,
messageService: MessageService,
) { super(messageService, http); }
login(login: string, password: string): Observable<User> {
// Error thrown on line below
return this.http.post<User>(environment.serverUrl + 'api/user/login', {'login': login, 'password': password}).pipe(
tap(user => this.log(`logged in ` + user)),
catchError(this.handleError('login'))
);
}
}
user.ts
import { BlogPost } from "./blog-post";
import { JobNote } from "./job-note";
import { BaseModel } from "./base-model";
export class User extends BaseModel {
id: number;
login: string;
name: string;
api_token: string;
isAdmin: boolean;
email: string;
address1: string;
address2: string;
address3: string;
phoneHome: string;
phoneWork: string;
phoneMobile: string;
fax: string;
blogPosts: BlogPost[];
notes: JobNote[];
}
base.service
import { Injectable } from '@angular/core';
import { User } from '../model/user';
import { ApprovedClaim } from '../model/approved-claim';
import { BlogCategory } from '../model/blog-category';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { MessageService } from './message.service';
import { throwError } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
export class BaseService {
constructor(
protected messageService: MessageService,
protected http: HttpClient,
) { }
protected handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
let errMsg = `error in ${operation}()`;
console.error(error); // log to console instead
this.log(`${operation} failed: ${error.message}`);
return throwError(errMsg);
};
}
protected log(message: string) {
this.messageService.add(message);
}
}
Changing from User to any
有人建议(删除答案)改变 Observable<User>
到 Observable<any>
,这编译但为什么?让它期望 User
对象作为响应之间的区别是什么 .
编辑:在参考重复标签时,我已经在做建议的答案了 . 错误消息也是关于可观察的User对象与用户不匹配,而不是空对象 .
1 回答
handleError
函数有一个泛型参数,如果不指定它,该函数将返回(error: any) => Observable<{} >
,在最终结果中引入{}
.试试这个 :