Angular HttpClient 需要 0 个类型参数,但得到 1 个

Tol*_*gon 0 api observable rxjs typescript angular

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

日历.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');
    }

}
Run Code Online (Sandbox Code Playgroud)

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}`);
  }


}
Run Code Online (Sandbox Code Playgroud)

日历-event.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;
}
Run Code Online (Sandbox Code Playgroud)

Kur*_*ton 6

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

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

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

  • 没问题。一开始它们很难理解,但一旦你开始理解它们,它们就会变得非常强大。我多年来一直在 C# 中使用它们,所以现在它们对我来说很自然。重要的是要记住,在 Typescript 中,仅仅因为您声明了一个类型,并不一定意味着您拥有该类型的实例。Typescript 只是编码时的助手。我们最终仍然只是编写 Javascript。 (2认同)