【问题标题】:Angular 6 cannot compile with error in serviceAngular 6 无法编译并出现服务错误
【发布时间】:2018-09-10 19:23:35
【问题描述】:

我是 Angular 6 的新手,但我使用它的次数越多,它的意义就越大。

我的服务有问题,连接到数据库

这是我在尝试 ng serve 时在 Angular CLI 中收到的错误消息

src/app/services/site.service.ts(29,5) 中的错误:错误 TS2322:类型 'Observable' 不可分配给类型 'Observable'。
类型“ISite”不可分配给类型“ISite[]”。 类型“ISite”中缺少属性“includes”。

这是我的界面

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

这是我的服务。

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

我已经检查了从数据库返回的内容是否与接口所期望的内容相匹配。

【问题讨论】:

    标签: angular6 angular-services


    【解决方案1】:

    getDeveloperSites 返回Observable&lt;ISite[]&gt;,但http.get 的类型为ISite(不带[])。将您的代码更改为以下内容,它应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2021-04-30
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多