【问题标题】:Angular HttpClient Expected 0 type arguments, but got 1Angular HttpClient 期望 0 个类型的参数,但得到 1
【发布时间】:2020-07-11 16:39:46
【问题描述】:

我有一项服务,我对我的 API 执行 http 请求,然后我为其他目的提供服务,将 url 传递给 http 请求服务。但是当我尝试将模型添加到我的 get 请求时,我收到了 Expected 0 type arguments, but got 1 错误。

calendar.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
// WebReq for http requests 
import { WebRequestService } from './web-request.service';
import { ICalendarEvent } from '../../models/calendar-event.model';


@Injectable({
    providedIn: 'root',
})

export class CalendarService {

    constructor(private webReqService: WebRequestService) { }

    // Where I get the error
    getCalendarEvent(): Observable<ICalendarEvent[]> {
        return this.webReqService.get<ICalendarEvent[]>('/calendars');
    }

}

web-request.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebRequestService {

  readonly _url: string;

  constructor(private http: HttpClient) {
    this._url = 'some url';
  }

  get(uri: string) {
    return this.http.get(`${this._url}/${uri}`);
  }

  post(uri: string, payload: Object) {
    return this.http.post(`${this._url}/${uri}`, payload);
  }

  patch(uri: string, payload: Object) {
    return this.http.patch(`${this._url}/${uri}`, payload);
  }

  delete(uri: string) {
    return this.http.delete(`${this._url}/${uri}`);
  }


}

日历事件.model.ts

export interface ICalendarEvent {
    id: number;
    start: string;
    end: string;
    title: string;
    estimate_number: string;
    brand: string;
    meters: string;
    floor: string;
    floor_type: string;
    plint_type: string;
    floor_installer: number;
    city: string;
    street: string;
    postal_code: string;
    province: string;
    notes: string;
}

【问题讨论】:

    标签: angular typescript api rxjs observable


    【解决方案1】:

    如果要调用带有类型参数的函数,则需要将泛型类型参数添加到声明中。

    如果您想获得这样做的全部好处,我建议您在函数中添加返回类型。

    get<T>(uri: string): Observable<T> {
      return this.http.get<T>(`${this._url}/${uri}`);
    }
    

    【讨论】:

    • 您的回答以及this documentation 帮助我更好地理解了这一点。谢谢库尔特
    • 没问题。一开始它们很难理解,但一旦你开始理解它们,它们就会变得强大。多年来我一直在 C# 中使用它们,所以现在它们对我来说很自然。重要的是要记住,在 Typescript 中,仅仅因为您声明了一个类型,并不一定意味着您拥有该类型的实例。 Typescript 只是一个编码时间的助手。我们最终还是只是在写 Javascript。
    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2021-08-22
    • 2019-08-28
    • 2020-11-07
    • 2023-04-06
    • 1970-01-01
    • 2018-10-22
    • 2018-09-19
    相关资源
    最近更新 更多