Reputation: 1399
In the postData() method on this line,
return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res.name);
It complains property name doesn't exist on type PostResponse[].
Here is complete code in the service,
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);
}
}
can someone tell me how to properly typecast and when to use PostResponse[] and PostResponse?
Upvotes: 2
Views: 123
Reputation: 13416
You are trying to access the name property of an array. You either need to access an index of the array
return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);
or change the type you are expecting
return this.http.post<PostResponse>(`${this.ROOT_URL}/users`, data).map(res => res.name);
EDIT - since your map method is returning a single string, your postData() method should return type 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;
}
Refer to AJT_82's stackblitz for a working demo (stackblitz.com/edit/angular-4mgpbw?file=app%2Fapp.component.ts)
Upvotes: 2