【发布时间】:2016-04-03 13:56:30
【问题描述】:
我在 Angular 中遇到了 HTTP 问题。
我只想GET 一个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] 中的函数
大厅中心组件
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"
]
}
【问题讨论】:
-
http.get 不返回一个承诺吗?
-
@bmm6o 新的
Http服务返回一个 observable -
我遇到了一个几乎相同的问题,试图将项目从 Angular2 beta-17 迁移到最终版本。对我来说,问题是我的 IDE,使用 VS 2015,Update 3。TypeScript 语言服务扩展仍然在
1.8.36,而 ng2 快速入门指南(在我写这篇文章时)使用的是"typescript": "^2.0.2"。升级 TS 语言。通过扩展和更新提供的服务对我有用。在安装该更新时,我遇到了this SO answer,它以相同的结论结束。 -
对于phpstorm/webstorm,用我项目的库更新typescript版本也解决了这个问题。我遵循了这个 SO 答案的步骤:stackoverflow.com/a/31608934/1291428