我是 Angular 的新手。
我该如何解决这个问题?
我已经安装了 Angular CLI: 11.0.7
和 Node: 12.18.4
错误:
<块引用>错误:src/app/_services/account.service.ts:19:7 - 错误 TS2345:
“OperatorFunction
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;
}
答案 0 :(得分:15)
你需要转换 http.post 返回
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);
}
})
)
}
答案 1 :(得分:0)
http.post 可以被类型转换为 User 或任何
也试试
login(model: any){
return this.http.post(this.baseUrl + 'account/login', model).pipe(
map((response: User)=>{
const user = response as User;
if(user){
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSource.next(user);
}
})
)
}
答案 2 :(得分:0)
Typescript: Type 'string | undefined' is not assignable to type 'string'
"strict": true >>>> "strict": false