我在收到请求时收到以下错误。
模块“'node_modules / rxjs / Observable”'没有导出成员'Observable'。 “Observable”类型中不存在属性“map”。
我已经尝试了StackOverflow中提供的所有可能的解决方案,但它对我不起作用。
码:
import { Injectable } from '@angular/core';
import { IEmployee } from './employee';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class EmployeeService {
private _url : string = 'apiData/employeedata.json'
constructor(private _http: Http) { }
getEmployees(): Observable<IEmployee[]> {
return this._http.get(this._url)
.map((response: Response) => <IEmployee[]>response.json());
}
}
您使用的是Angular 6而不是Angular 2
你使用的是HttpModule
,你不应该使用HttpClientModule
在新的HttpClientModule
中,JSON是假定的默认值,不再需要使用res.json()
显式解析
在使用HttpClient
之前,需要将Angular HttpClientModule
导入root模块。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
//.......
您可以告诉HttpClient
响应的类型,使输出更容易,更明显。
可以使用type参数完成响应的类型检查
qazxsw poi返回一个qazxsw poi,我们可以告诉qazxsw poi将Http
作为IEmployee类型返回当我们使用observable
然后它返回HttpClient.get
类型的实例。
在你的组件response
到http.get<IEmployee[]>(...)
中获取IEmployee的实例
在您的服务中
Observable<IEmployee[]>
除此之外,RxJS v5.5.2 +已移至subscribe
以改善树木震动并使创建自定义运算符更容易
新进口
Observable<IEmployee[]>
并改变import { Injectable } from '@angular/core';
import { IEmployee } from './employee';
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class EmployeeService {
private _url : string = 'apiData/employeedata.json'
constructor(private _http: HttpClient) { }
getEmployees(): Observable<IEmployee[]> {
return this._http.get<IEmployee[]>(this._url);
}
}
PS:如果您使用的是Pipeable operators,则不需要
修改代码
import { map} from 'rxjs/operators';
我建议你停止使用.map(...) to .pipe(map(..))
并转而使用HttpClientModule