Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error TS2345: Argument of type 'OperatorFunction<User, void>' is not assignable to parameter of type 'OperatorFunction<Object, void>'

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;
}

The error

like image 589
Roohi Avatar asked Jan 24 '21 23:01

Roohi


1 Answers

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);
        }
      })
    )
  }
like image 165
Rachid O Avatar answered Oct 21 '22 01:10

Rachid O