![](/img/trans.png)
[英]The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead
[英]The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
我有一個相當復雜的代碼已經運行了兩天,我正在使用 rxjs 運算符中的 map 運算符從IUser
接口中獲取IUser
的值。 但我不斷收到此錯誤:
“OperatorFunction<IUser, void>”類型的參數不可分配給“OperatorFunction<Object, void>”類型的參數。 “對象”類型可分配給極少數其他類型。 您的意思是改用“任何”類型嗎? 類型“對象”缺少類型“IUser”中的以下屬性:email、顯示名稱、令牌。
提前致謝。
賬戶.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { IUser } from '../shared/models/user';
@Injectable({
providedIn: 'root'
})
export class AccountService {
baseUrl = environment.apiUrl;
private currentUserSource = new BehaviorSubject<IUser>(null!);
currentUser$ = this.currentUserSource.asObservable();
constructor(private http: HttpClient, private router: Router) { }
login(values: any) {
return this.http.post(this.baseUrl + 'account/login', values).pipe(
map((user: IUser) => {
if (user) {
localStorage.setItem('token', user.token);
this.currentUserSource.next(user)
}
})
);
}
登錄組件.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
用戶.ts
export interface IUser {
email: string;
displayName: string;
token: string;
}
超載#14
post(url: string, body: any | null, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
observe?: 'body';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<Object>;
如果沒有為.post()
[Overload #14] 指定T
,它將返回Observable<Object>
值。
超載#15
post<T>(url: string, body: any | null, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
observe?: 'body';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
從post()
[Overload #15],你必須指定T
例如post<T>()
,這樣它會返回Observable<T>
值。
假設:返回的響應是IUser
類型。
login(values: any) {
return this.http.post<IUser>(this.baseUrl + 'account/login', values).pipe(
tap((user: IUser) => {
if (user) {
localStorage.setItem('token', user.token);
this.currentUserSource.next(user);
}
})
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.