天道酬勤,学无止境

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

Typescript: Type 'string | undefined' is not assignable to type 'string'

"strict": true >>>> "strict": false

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 'MonoTypeOperatorFunction 类型的参数 ' 不能分配给类型为 'UnaryFunction 的参数(Argument of type 'MonoTypeOperatorFunction<any>' is not assignable to parameter of type 'UnaryFunction<Observable<any>, Observable<any>>')
    问题 我正在尝试从rxjs 5 迁移到 6,但我遇到了困难。 当我尝试这个时 this._connectivity.isOnline().pipe(first()).subscribe((state) => { this.syncCheck(user.uid); }); 我收到这个错误 Argument of type 'MonoTypeOperatorFunction<any>' is not assignable to parameter of type 'UnaryFunction<Observable<any>, Observable<any>>'. Types of parameters 'source' and 'source' are incompatible. Type 'import("/home/User/Desktop/projectname/node_modules/rxjs/Observable").Observable<any>' is not assignable to type 'import("/home/User/Desktop/projectname/node_modules/rxjs/internal/Observable").Observable<a...'. Property 'map' is missing in type
  • 转换为函数时无法编译代码(unable to compile a code when converted into a function)
    问题 我有以下代码可以正常工作。 public createData(data:Data):Observable<any>{ console.log('contacting server at '+this.API_URL +this.NEW_DATA_URL +" with data "+data+ " with httpOptions "+httpOptions.withCredentials + ","+httpOptions.headers ); let newData = new Data(data) let body = JSON.stringify(newQuestion); //I WANT TO MOVE THE CODE BELOW INTO A FUNCTION BUT AM GETTING COMPILATION ERROR this.loaderService.show(); return this.http.post(this.NEW_QUESTION_URL,body,httpOptions) .pipe(tap(response => { let httpEvent = <HttpEvent<any>>response; if(httpEvent.type === HttpEventType.Response) { console.log(
  • TypeScript 泛型:泛型函数类型和对象文字类型的调用签名不等价(类型“T”不可分配给类型“T”)(TypeScript generics: Inequivalence of generic function type and call signature of an object literal type (Type 'T' is not assignable to type 'T'))
    问题 我正在编写一个 RxJS 运算符,它等待输入运算符完成,然后对第二个运算符执行switchMap (与switchMap一样switchMap )。 我想出了两个版本的代码,一个有效,一个无效,我正在努力弄清楚为什么会这样。 有效的版本: import { Observable } from "rxjs"; // OperatorFunction, import { defaultIfEmpty, last, switchMap } from "rxjs/operators"; // This definition of OperatorFunction is more or less equivalent to the // definition in rxjs/src/internal/types.ts interface OperatorFunction<T, S> { (input: Observable<T>): Observable<S>; } interface ObservableGenerator<T, S> { (value: T): Observable<S>; } export function switchMapComplete<T, S>(project: ObservableGenerator<T, S>): OperatorFunction<T
  • How to pipe / map an Observable in Angular
    A nested object is showing up as [object Object] so I'm trying to cast it via pipe and map but I'm not getting any where. I've tried the models as classes and interfaces but no help. Can someone tell me what I'm doing wrong? Thanks. The function: getClients(customerId: number): Observable<Client[]> { let clientUrl = 'SOME_URL'; return this.http.get<Client[]>(clientUrl) .pipe(map(client: Client) => client.address as Address); } The models: import { Address } from './address.model'; export class Client{ id: number; name: string; accountNumber: string; addressId: number; phoneNumber: string
  • TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'
    I am trying to create a chrome extension in typescript. I have the following code, where I try to send a message to contentscript from the background script. // background script chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) { console.log(response); }); }); but typescript is giving the following error ERROR in /Users/shobi/Projects/Chrome Extensions/src/js/background.ts(8,37) TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined'
  • TypeScript generics: Inequivalence of generic function type and call signature of an object literal type (Type 'T' is not assignable to type 'T')
    I'm writing an RxJS operator which waits for the input operator to complete and then does a switchMap to a second operator (which is generated on the fly just as with switchMap). I have come up with two versions of my code, one which works and one which doesn't and I'm struggling to wrap my head around why that is. The version that works: import { Observable } from "rxjs"; // OperatorFunction, import { defaultIfEmpty, last, switchMap } from "rxjs/operators"; // This definition of OperatorFunction is more or less equivalent to the // definition in rxjs/src/internal/types.ts interface
  • Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345)
    I have index.html <body> <div id="portal"></div> <div id="root"></div> </body> and want to use the component below in separate portal div than root div, import React from 'react'; const portalDiv = document.getElementById('portal'); function Portal1(props) { return ReactDOM.createPortal( <div> {props.children} <div/>, portalDiv); //here } export default Portal1; But I am getting this error, Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345) in VScode. I am using Typescript.
  • Argument Type Observable<User[]> is not assignable to parameter of type User[]
    I'm trying to adapt the material examples like the following: import { Component } from '@angular/core'; import { MatTableDataSource } from '@angular/material'; import { User } from '../models/user.model'; import { XService } from './x.service'; @Component({ selector: 'x-component', styleUrls: ['x.component.css'], templateUrl: 'x.component.html', }) export class XComponent { constructor(private xService: XService) { } displayedColumns = ['c1', 'c2', 'c3', 'c4']; dataSource = new MatTableDataSource<User>(this.xService.getUsers()); applyFilter(filterValue: string) { filterValue = filterValue
  • unable to compile a code when converted into a function
    I have the following piece of code which works correctly. public createData(data:Data):Observable<any>{ console.log('contacting server at '+this.API_URL +this.NEW_DATA_URL +" with data "+data+ " with httpOptions "+httpOptions.withCredentials + ","+httpOptions.headers ); let newData = new Data(data) let body = JSON.stringify(newQuestion); //I WANT TO MOVE THE CODE BELOW INTO A FUNCTION BUT AM GETTING COMPILATION ERROR this.loaderService.show(); return this.http.post(this.NEW_QUESTION_URL,body,httpOptions) .pipe(tap(response => { let httpEvent = <HttpEvent<any>>response; if(httpEvent.type ===
  • Angular 2 + Jasmine Unit Test - Getting Error TS2345
    I followed the unit testing from this website (author: Torgeir Helgevold) @:TGH http://www.syntaxsuccess.com/viewarticle/angular-2.0-unit-testing to do unit testing, but got an error: "Error:(15, 39) TS2345: Argument of type 'FunctionWithParamTokens' is not assignable to parameter of type '(done: () => void) => void'." it('should define full name2', inject([DisplayName], (displayName) => { displayName.firstName = 'Joe'; displayName.lastName = 'Smith'; displayName.generateFullName(); expect(displayName.fullName).toBe('Joe Smith'); })); Is the code in this website out of date? Can anyone give me
  • Angular 6 & RxJS 6 Breaking Changes
    I've google the crap out of this and I can't find a solution. I've been using code like this for some time now. http is the angular HttpClient. forgotPassword(email: string): Observable<ApiReturn> { const url = `${this.apiURL}/ForgotPassword`; const params = { email }; return this.http .post<ApiReturn>(url, params, this.requestOptions) .pipe(catchError(e => this.handleError(e))); } I updated to the latest Angular 6.x version and RxJS 6 (from 5.5). Now the code is complaining about the catchError: Argument of type 'OperatorFunction' is not assignable to parameter of type 'OperatorFunction'
  • How to add strongly typed field in Formik by typescript?
    I tried to add strongly typed in Formik react library by typescript, but I didn't do that. Of course, I have used this link, but I couldn't solve my issue. https://jaredpalmer.com/formik/docs/guides/typescript I have got this error from this part of code(})(ActivityForm);): Argument of type '(props: IProps) => Element' is not assignable to parameter of type 'CompositeComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'. Type '(props: IProps) => Element' is not assignable to type 'FunctionComponent & FormikState & FormikHelpers &
  • TypeScript rejection with `Type '{}[]' is not assignable to type 'number'`
    Let's say I create a simple function to double its input, > let f1: (x: number) => number = x => x * 2; > .type f1 let f1: (x: number) => number If I want to take the first value and double it, I can do either let f2 = R.pipe( R.take(1), f1 ); let f2 = R.pipe( R.head, f1 ); Both of these work f2([5,4,3]) outside of TypeScript. However, with TypeScript I get, > let f2 = R.pipe( R.take(1), f1 ); [eval].ts(6,29): error TS2345: Argument of type '(x: number) => number' is not assignable to parameter of type '(x: {}[]) => number'. Types of parameters 'x' and 'x' are incompatible. Type '{}[]' is not
  • Vue&TypeScript: how to avoid error TS2345 when import implemented in TypeScript component outside of project directory?
    I got below TypeScript error when tried to use side component (outside of project directory): TS2345: Argument of type '{ template: string; components: { SimpleCheckbox: typeof SimpleCheckbox; }; }' is not assignable to parameter of type 'VueClass<Vue>'. Object literal may only specify known properties, and 'template' does not exist in type 'VueClass<Vue>'. My WebStorm IDE did not detect this error; in was outputted in console when I ran Webpack with TypeScript loader. The error occurs in: import { Vue, Component, Prop } from 'vue-property-decorator'; import template from '
  • Typing redux forms v7 with TypeScript and React
    I've got a plain react-redux-powered form. I wish for there to be a form.container.tsx and a form.component.tsx, where form.container.tsx holds all the connections to redux state minus the Field's. I'm trying to wrap my container in react-redux's connect and then wrapping reduxForm within it to look something like TypeScript, redux-form and connect: (ideal) form.container.tsx: interface DummyFormContainerProps {} export const DummyFormContainer: React.SFC<DummyFormContainerProps> = props => { const submitForm = (formValues: object) => { alert(formValues); }; return ( <DummyForm onSubmit=
  • Argument of type '(snap: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'
    I've already read several questions and answers about this problem but wasn't able to solve it. I'm using Ionic2 and I have a method which retrieves data from Firebase Database v3. I don't understand why I get following error in console when I do ionic serve: Error TS2345: Argument of type '(snap: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'. Type 'void' is not assignable to type 'boolean'. This is the method: constructor(private http: Http) { firebase.database().ref('users').orderByChild("id").on("value", function(snapshot){ let items = []
  • Accept any object as argument in function
    What I have I have a method in a class which I want to accept any object as an argument but I don't want to use any, for this I use a generic and extend object. class MyClass { saveObject<T extends object>(object: T | null) {} } With this implementation, @typescript-eslint/ban-types rule complains with the following error: Don't use 'object' as a type. The 'object' type is currently hard to use see this issue(https://github.com/microsoft/TypeScript/issues/21732)). Consider using 'Record<string, unknown>' instead, as it allows you to more easily inspect and use the keys. ok, then I will listen
  • 类型“OperatorFunction”上不存在属性“subscribe” '(Property 'subscribe' does not exist on type 'OperatorFunction<unknown, any>')
    问题 我正在尝试从mongodb获取一些数据,并不断收到此错误: “OperatorFunction”类型上不存在“订阅”属性 //app.component.ts import { Component } from '@angular/core'; import {FormGroup, FormControl, Validators, FormsModule} from '@angular/forms'; import {CommonService} from './common.service'; import {Http, Response, Headers, RequestOptions} from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { map } from 'rxjs/operators'; import { from } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private
  • '(snap: DataSnapshot) => void' 类型的参数不可分配给类型 '(a: DataSnapshot) => boolean' 的参数(Argument of type '(snap: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean')
    问题 我已经阅读了有关此问题的几个问题和答案,但无法解决。 我正在使用 Ionic2,并且有一种方法可以从 Firebase 数据库 v3 中检索数据。 我不明白为什么在执行ionic serve时会在控制台中出现以下错误: Error TS2345: Argument of type '(snap: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'. Type 'void' is not assignable to type 'boolean'. 这是方法: constructor(private http: Http) { firebase.database().ref('users').orderByChild("id").on("value", function(snapshot){ let items = []; snapshot.forEach(snap => { items.push({ uid: snap.val().uid, username: snap.val().username, }); }); }); } } 回答1 DataSnapshot的forEach方法具有以下签名: forEach(action: (a
  • 如何通过打字稿在 Formik 中添加强类型字段?(How to add strongly typed field in Formik by typescript?)
    问题 我试图通过打字稿在 Formik 反应库中添加强类型,但我没有这样做。 当然,我已经使用了这个链接,但我无法解决我的问题。 https://jaredpalmer.com/formik/docs/guides/typescript 我从这部分代码(})(ActivityForm);)中得到了这个错误: '(props: IProps) => Element' 类型的参数不可分配给'CompositeComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'。 类型 '(props: IProps) => Element' 不可分配给类型 'FunctionComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'。 参数 'props' 和 'props' 的类型不兼容。 “FormikSharedConfig<{}> & FormikState & FormikHelpers & FormikHandlers &