简体   繁体   中英

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

错误

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM