Reputation: 8783
I'm new to Angular.
How can I solve this problem?
I have installed Angular CLI: 11.0.7
and Node: 12.18.4
Error:
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;
}
Upvotes: 20
Views: 22242
Reputation: 1
Typescript: Type 'string | undefined' is not assignable to type 'string'
"strict": true >>>> "strict": false
Upvotes: -3
Reputation: 14052
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);
}
})
)
}
Upvotes: 61
Reputation: 1
http.post can be typecast to User or any
also try
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);
}
})
)
}
Upvotes: 0