angular9 generi c http звонки с использованием dataservice - PullRequest
0 голосов
/ 01 апреля 2020

Проблема:

return this.entitesService.getEntities().pipe(
      tap((result: GetEntitiesResponse) => {
        console.log(typeof result);
        console.log('RESULT:', result);
      })
    );

В этой строке есть ошибка, несовместимая с типом:

tap((result: GetEntitiesResponse) => {

Если я удалю тип или определю его как любой - тогда есть Нет ошибки. Но я хочу, чтобы типы были везде.

Вероятно, проблема в определении службы данных.

Текущее текстовое сообщение об ошибке:

Argument of type 'MonoTypeOperatorFunction<GetEntitiesResponse>' is not assignable to parameter of type 'OperatorFunction<HttpEvent<GetEntitiesResponse>, GetEntitiesResponse>'.
  Types of parameters 'source' and 'source' are incompatible.
    Type 'Observable<HttpEvent<GetEntitiesResponse>>' is not assignable to type 'Observable<GetEntitiesResponse>'.
      Type 'HttpEvent<GetEntitiesResponse>' is not assignable to type 'GetEntitiesResponse'.
        Type 'HttpSentEvent' is missing the following properties from type 'GetEntitiesResponse': data, metats(2345)

Служба данных:

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  protected url: string;

  constructor(private http: HttpClient) {}

  get<T>(endpoint: string, obj: object = null) {
    return this.http.get<T>(this.url + endpoint, this.getHttpParams(obj));
  }

  protected getHttpParams(obj: object) {
    const requestOptions: any = {};
    requestOptions.headers = new HttpHeaders({
      Accept: 'application/json',
      'Content-Type': 'application/json'
    });

    if (obj !== null) {
      requestOptions.params = this.objectToHttpParams(obj);
    }

    return requestOptions;
  }

  protected objectToHttpParams(obj: object): HttpParams {
    let params = new HttpParams();
    for (const key of Object.keys(obj)) {
      params = params.set(key, (obj[key] as unknown) as string);
    }

    return params;
  }
}

Является ли это правильным определением для передачи типа generi c в angular http?

  get<T>(endpoint: string, obj: object = null) {
    return this.http.get<T>(this.url + endpoint, this.getHttpParams(obj));
  }

Или должен быть другой синтаксис.

И вот услуга:

export class EntitiesService extends ApiService {
  constructor(http: HttpClient) {
    super(http);
  }

  getEntities(): Observable<HttpEvent<GetEntitiesResponse>> {
    return this.get<GetEntitiesResponse>('/entities');
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...