我在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());
}
}
Run Code Online (Sandbox Code Playgroud)
在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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我有一个例外:
TypeError:this.http.get(...).map不是[null]中的函数 …
我试图在我的代码中使用以下服务:
import {Injectable} from '@angular/core';
import {Http,Response} from "@angular/http";
import 'rxjs/Rx';
@Injectable()
export class HttpService{
constructor(private http : Http){}
getData(){
return this.http.get("URI")
.map( (res: Response) => res.json() );
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在运行时它抱怨:
res.json is not a function
Run Code Online (Sandbox Code Playgroud)
我已将res的数据类型定义为Response,但仍然抱怨
.map( (res: Response) => res.json() )
Run Code Online (Sandbox Code Playgroud)
如果我用订阅替换地图它工作正常:
.subscribe( res =>{
res.json();
console.log("City is:"+ res.json().city.name)
});
Run Code Online (Sandbox Code Playgroud)