错误 TS2345:“OperatorFunction<User, void>"类型的参数不可分配给“OperatorFunction<Object, void>"类型的参数 [英] error TS2345: Argument of type 'OperatorFunction<User, void>' is not assignable to parameter of type 'OperatorFunction<Object, void>'
问题描述
我是 Angular 的新手.
I'm new to Angular.
我该如何解决这个问题?
How can I solve this problem?
我已经安装了 Angular CLI: 11.0.7
和 Node: 12.18.4
错误:
错误:src/app/_services/account.service.ts:19:7 - 错误 TS2345:'OperatorFunction
Error: src/app/_services/account.service.ts:19:7 - error TS2345: Argument of type 'OperatorFunction<User, void>' is not assignable to parameter of type 'OperatorFunction<Object, void>'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 'User': username, token
19 map((response: User) => {
~~~~~~~~~~~~~~~~~~~~~~~~~
20 const user = response;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
24 }
~~~~~~~~~
25 })
~~~~~~~~
account.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {map} from 'rxjs/operators';
import { User } from '../_models/user';
import { ReplaySubject } from 'rxjs';
export class AccountService {
baseUrl = 'https://localhost:5001/api/';
private currentUserSource = new ReplaySubject<User>(1);
currentUser$ = this.currentUserSource.asObservable();
constructor(private http: HttpClient) { }
login(model: any) {
return this.http.post(this.baseUrl + 'account/login', model).pipe(
map((response: User) => {
const user = response;
if (user) {
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSource.next(user);
}
})
)
}
}
user.ts
export interface User{
username: string;
token: string;
}
推荐答案
你需要强制转换 http.post 返回
you need to cast the http.post return
login(model: any) {
//-------------- here ⇊⇊ ------
return this.http.post<User>(this.baseUrl + 'account/login', model).pipe(
map((user : User) => {
if (user) {
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSource.next(user);
}
})
)
}
这篇关于错误 TS2345:“OperatorFunction<User, void>"类型的参数不可分配给“OperatorFunction<Object, void>"类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!