错误 TS2345:“OperatorFunction<User, void>"类型的参数不可分配给“OperatorFunction<Object, void>"类型的参数 [英] error TS2345: Argument of type &#39;OperatorFunction&lt;User, void&gt;&#39; is not assignable to parameter of type &#39;OperatorFunction&lt;Object, void&gt;&#39;

查看:28
本文介绍了错误 TS2345:“OperatorFunction<User, void>"类型的参数不可分配给“OperatorFunction<Object, void>"类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 的新手.

I'm new to Angular.

我该如何解决这个问题?

How can I solve this problem?

我已经安装了 Angular CLI: 11.0.7Node: 12.18.4

错误:

错误:src/app/_services/account.service.ts:19:7 - 错误 TS2345:'OperatorFunction' 类型的参数不可分配给'OperatorFunction' 类型的参数.对象"类型可分配给很少的其他类型.您是想改用any"类型吗?对象"类型缺少用户"类型中的以下属性:用户名、令牌

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆