我是Angular 6的新用户,但使用得越多,它的意义就越大。
我的服务无法连接到数据库
这是我尝试ng serve
src / app / services / site.service.ts(29,5)中的ERROR:错误TS2322:类型 无法将“可观察”分配给“可观察”类型。
类型“ ISite”不可分配给类型“ ISite []”。 类型“ ISite”中缺少属性“包含”。
这是我的界面
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");
}
}
我已经检查了从数据库返回的内容是否与接口所期望的相匹配,并且它们相匹配。
答案 0 :(得分:0)
getDeveloperSites
返回Observable<ISite[]>
,但是http.get
的类型为ISite(不带[])。将您的代码更改为以下代码,它应该可以工作:
getDeveloperSites(id: string): Observable<ISite[]> {
let url = `${this._url}/developer/${id}`;
return this.http.get<ISite[]>(url)
.pipe(catchError(this.errorHandler));
}