我在Angular中的HTTP有一个问题。

我只是想获得一个JSON列表,并在视图中显示它。

服务类

import {Injectable} from "angular2/core";
import {Hall} from "./hall";
import {Http} from "angular2/http";
@Injectable()
export class HallService {
    public http:Http;
    public static PATH:string = 'app/backend/'    

    constructor(http:Http) {
        this.http=http;
    }

    getHalls() {
           return this.http.get(HallService.PATH + 'hall.json').map((res:Response) => res.json());
    }
}

在HallListComponent中,我从服务中调用getHalls方法:

export class HallListComponent implements OnInit {
    public halls:Hall[];
    public _selectedId:number;

    constructor(private _router:Router,
                private _routeParams:RouteParams,
                private _service:HallService) {
        this._selectedId = +_routeParams.get('id');
    }

    ngOnInit() {
        this._service.getHalls().subscribe((halls:Hall[])=>{ 
            this.halls=halls;
        });
    }
}

然而,我有一个例外:

TypeError: this.http.get(……)。Map不是[null]中的函数

hall-center.component

import {Component} from "angular2/core";
import {RouterOutlet} from "angular2/router";
import {HallService} from "./hall.service";
import {RouteConfig} from "angular2/router";
import {HallListComponent} from "./hall-list.component";
import {HallDetailComponent} from "./hall-detail.component";
@Component({
    template:`
        <h2>my app</h2>
        <router-outlet></router-outlet>
    `,
    directives: [RouterOutlet],
    providers: [HallService]
})

@RouteConfig([
    {path: '/',         name: 'HallCenter', component:HallListComponent, useAsDefault:true},
    {path: '/hall-list', name: 'HallList', component:HallListComponent}
])

export class HallCenterComponent{}

app.component

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from "angular2/router";
import {RouteConfig} from "angular2/router";
import {HallCenterComponent} from "./hall/hall-center.component";
@Component({
    selector: 'my-app',
    template: `
        <h1>Examenopdracht Factory</h1>
        <a [routerLink]="['HallCenter']">Hall overview</a>
        <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
    {path: '/hall-center/...', name:'HallCenter',component:HallCenterComponent,useAsDefault:true}
])
export class AppComponent { }

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

当前回答

对于Angular 5及以上版本,更新后的导入行看起来是这样的:

import { map } from 'rxjs/operators';

OR

import { map } from 'rxjs/operators';

此外,这些版本完全支持Pipable操作符,因此您可以轻松使用.pipe()和.subscribe()。

如果你使用的是Angular版本2,那么下面这行代码应该可以正常工作:

import 'rxjs/add/operator/map';

OR

import 'rxjs/add/operators/map';

如果你仍然遇到问题,那么你必须这样做:

import 'rxjs/Rx';

我不喜欢你直接使用它,因为它增加了加载时间,因为它有大量的操作符(有用的和无用的),这不是一个好的实践,根据行业规范,所以一定要先尝试使用上面提到的导入行,如果这不起作用,那么你应该去rxjs/Rx

其他回答

加上@mlc-mlapis所评论的,您混合了可让操作符和原型修补方法。使用其中之一。

对你的案子来说应该是

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable()
export class SwPeopleService {
    people$ = this.http.get('https://swapi.co/api/people/')
      .map((res:any) => res.results);

    constructor(private http: HttpClient) {} 
}

https://stackblitz.com/edit/angular-http-observables-9nchvz?file=app%2Fsw-people.service.ts

这是因为你正在使用RXJS,在RXJS函数不是静态的,这意味着你不能直接调用它们,你必须调用管道内的方法,并从RXJS库导入该函数

但是如果你正在使用rxjs-compat,那么你只需要导入rxjs-compat操作符

import 'rxjs/add/operator/map';

会解决你的问题

我在angular 5.2.0和rxjs 5.5.2中测试了它

使用可观察到的。直接订阅应该有用。

@Injectable()
export class HallService {
    public http:Http;
    public static PATH:string = 'app/backend/'    

    constructor(http:Http) {
        this.http=http;
    }

    getHalls() {
    // ########### No map
           return this.http.get(HallService.PATH + 'hall.json');
    }
}


export class HallListComponent implements OnInit {
    public halls:Hall[];
    / *** /
    ngOnInit() {
        this._service.getHalls()
           .subscribe(halls => this.halls = halls.json()); // <<--
    }
}

Angular版本6 "0.6.8" RXJS版本6 "^6.0.0"

此解决方案适用于:

  "@angular-devkit/core": "0.6.8",
  "rxjs": "^6.0.0"

我们都知道angular每天都在开发,所以每天都有很多变化,这个解决方案是针对angular 6和RXJS 6的 首先要使用HTTP,你应该导入它从: 毕竟你必须在app.module.ts中声明HttpModule

import { Http } from '@angular/http';

你必须将HttpModule添加到Ngmodule -> imports中

  imports: [
    HttpModule,
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
  ],

第二,使用map,你应该首先导入管道:

import { pipe } from 'rxjs';

第三,你需要从下面导入map函数:

import { map } from 'rxjs/operators';

你必须像下面这个例子一样在管道中使用map:

 constructor(public http:Http){  }

    getusersGET(){
        return this.http.get('http://jsonplaceholder.typicode.com/users').pipe(
         map(res => res.json()  )  );
    }

那太好了祝你好运!