簡體   English   中英

打字稿抱怨 PostResponse[] 類型上不存在屬性名稱

[英]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);
   }
}

有人能告訴我如何正確類型轉換以及何時使用 PostResponse[] 和 PostResponse? 錯誤的屏幕截圖

您正在嘗試訪問數組的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM