![](/img/trans.png)
[英]Error: "Property '.get' doesn't exist on type 'JSON' (HTML / Javascript / Angular2 / Typescript)
[英]Typescript complains property name doesn't exist on type PostResponse[]
在這一行的 postData() 方法中,
return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res.name);
它抱怨 PostResponse[] 類型上不存在屬性名稱。
這是服務中的完整代碼,
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ItemsResponse } from './data.interface';
import 'rxjs/add/operator/map';
interface PostResponse {
data: [
{
name: string;
job: string;
}
];
}
@Injectable()
export class RepositoryService {
readonly ROOT_URL = 'https://reqres.in/api';
constructor (private http: HttpClient) {
console.log('idea repository service instance');
}
postData(): Observable<PostResponse> {
const data = [ {
name: 'Morpheus',
job: 'Developer'
} ];
return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);
}
}
您正在嘗試訪問數組的 name 屬性。 您要么需要訪問數組的索引
return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);
或更改您期望的類型
return this.http.post<PostResponse>(`${this.ROOT_URL}/users`, data).map(res => res.name);
編輯- 由於您的 map 方法返回單個字符串,因此您的 postData() 方法應返回類型Observable<string>
postData(): Observable<string> {
const data = [{
name: 'Morpheus',
job: 'Developer'
}];
return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);
}
// interface
export interface PostResponse {
name: string;
job: string;
}
有關工作演示,請參閱 AJT_82 的 stackblitz (stackblitz.com/edit/angular-4mgpbw?file=app%2Fapp.component. ts)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.