Search code examples
angular6angular-services

Angular 6 cannot compile with error in service


I am new ti Angular 6 but it's starting to make a lot more sense the more I use it.

I have a problem with my service that connects to a database

Here is the error message I get in Angular CLI when trying to ng serve

ERROR in src/app/services/site.service.ts(29,5): error TS2322: Type 'Observable' is not assignable to type 'Observable'.
Type 'ISite' is not assignable to type 'ISite[]'. Property 'includes' is missing in type 'ISite'.

This is my interface

export interface ISite {
  id: string,
  siteName: string,
  developer: string,
  siteAddress: string,
  siteAddress2: string,
  siteCity: string,
  siteCounty: string,
  sitePostcode: string,
}

This is my service.

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { ISite } from './../interfaces/site';
import { throwError as observableThrowError, Observable } from 'rxjs'
import { catchError } from 'rxjs/operators'

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

  private _url: string = "http://localhost/lumen/public/sites";

  constructor(private http: HttpClient) { }

  getSites(): Observable<ISite[]> {
    return this.http.get<ISite[]>(this._url)
               .pipe(catchError(this.errorHandler));
  }

  getSite(id: string): Observable<ISite> {
    let url = `${this._url}/${id}`;
    return this.http.get<ISite>(url)
               .pipe(catchError(this.errorHandler));
  }

  getDeveloperSites(id: string): Observable<ISite[]> {
    let url = `${this._url}/developer/${id}`;
    return this.http.get<ISite>(url)
           .pipe(catchError(this.errorHandler));
  }

  errorHandler(error: HttpErrorResponse) {
    return observableThrowError(error.message || "Server Error");
  }
}

I've checked what comes back from the database matches what the interface is expecting and they match.


Solution

  • getDeveloperSites returns Observable<ISite[]>, but http.get is given the type ISite (without []). Change your code to the following and it should work:

    getDeveloperSites(id: string): Observable<ISite[]> {
        let url = `${this._url}/developer/${id}`;
        return this.http.get<ISite[]>(url)
               .pipe(catchError(this.errorHandler));
      }