json - 角 HTTP GET
问题描述
- 我有一个在“localhost:3000”上运行的服务器。它将数据显示为 JSON,例如“localhost:300/locations”。
- 我的“data.service.ts”包括以下代码:
path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }
// Locations
getAllLocations(): Observable<Location[]> {
let location = null;
this.http.get(this.path + '/locations')
.map((res => location = res))
.catch((error: any) => Observable.throw(console.log(error)));
return location;
}
- 在我的 result.component.ts 中,我正在运行以下代码:
constuctor(private dataservice: DataService) { }
ngOnInit() {
console.info(this.dataservice.getAllLocations());
}
我期望将所有位置作为 JSON 的输出,而不是输出为“null”。
有人对如何使其正常工作有任何建议吗?
更新:还尝试了 HTTP 调用:
getAllLocations(): Observable<Location[]> {
this.http.get<Location[]>(this.path + '/locations')
.pipe(
tap(items => console.info('fetched items'))
);
}
解决方案
您必须从服务中返回 Observable:
path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }
// Locations
getAllLocations(): Observable<Locations[]> {
return this.http.get(this.path + '/locations')
.map((res => location = res))
.catch((error: any) => Observable.throw(console.log(error)));
}
并在组件中订阅它。
constructor(private dataservice: DataService) { }
ngOnInit() {
this.dataservice.getAllLocations().subscribe(result => {
console.log(result);
})
}
推荐阅读
- templates - 带有条件的 OCP 自定义模板
- c - 替换数组的打印字符
- html - DOM 节点在我的 Angular 中不断增加
- c# - 为什么此代码仅在第二次运行时才有效?
- swift - 如何修复 UIcollectionViewCell 显示空单元格?
- visual-studio-code - VScode远程'_workbench.downloadResource'失败
- java - 如何使用springboot将数据从数据库动态更新到图表(highchart)
- javascript - 我同时使用 React 和 Google Translation api。还有一个问题
- python-3.x - Discord 命令不完全起作用,有什么想法吗?
- java - 处理重复的方法头