简体   繁体   English

打字稿抱怨 PostResponse[] 类型上不存在属性名称

[英]Typescript complains property name doesn't exist on type PostResponse[]

In the postData() method on this line,在这一行的 postData() 方法中,

return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res.name);

It complains property name doesn't exist on type PostResponse[].它抱怨 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?有人能告诉我如何正确类型转换以及何时使用 PostResponse[] 和 PostResponse? 错误的屏幕截图

You are trying to access the name property of an array.您正在尝试访问数组的 name 属性。 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>编辑- 由于您的 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;
}

Refer to AJT_82's stackblitz for a working demo (stackblitz.com/edit/angular-4mgpbw?file=app%2Fapp.component.‌​ts)有关工作演示,请参阅 AJT_82 的 stackblitz (stackblitz.com/edit/angular-4mgpbw?file=app%2Fapp.component.‌ ts)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM