微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 2 HTTP GET与TypeScript错误http.get(…).map不是一个函数在[null]

我在Angular 2中有一个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 is not a function in [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"
  ]
}

对不起,长的帖子…

我认为你需要导入这:
import 'rxjs/add/operator/map'

或者更一般地说,如果你想有更多的方法观察:

import 'rxjs/Rx';

有关详细信息,请参阅this issue

原文地址:https://www.jb51.cc/angularjs/147358.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐