在这一行的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);
}
}
答案 0 :(得分:2)
您正在尝试访问数组的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./)