Angular 2:属性'map'在'Observable'类型上不存在 “

问题描述 投票:1回答:1

我在收到请求时收到以下错误。

模块“'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
1个回答
2
投票

您使用的是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类型的实例。

在你的组件responsehttp.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

© www.soinside.com 2019 - 2024. All rights reserved.