我在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]中的函数 …
使用服务在Angular 2应用程序中存储(和共享)初始值的最佳实践是什么?我有一个服务,从服务器加载大量数据作为资源,配置和其他数组和对象.我不希望每次加载组件或路由到视图时都加载此数据,我只想在应用程序启动时使用这些对象和已加载的数组,并根据需要重新加载.问题是存储此值的正确位置以及如何在使用该服务的组件之间共享?谢谢.