我正在尝试从服务器获取 jSon 并将其映射到 Angular 5 应用程序中的类。以下是没有错误的服务方法:
getSearchResultTable(hash: number): Observable<Model.SearchResult.RootObject> {
return this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
.map(res => new Model.SearchResult.RootObject());
return tmp;
}
以下组件类:
export class SearchResultPageComponent implements OnInit {
searchResult: Model.SearchResult.RootObject;
constructor(private searchResultService: SearchResultService, private router: Router) { }
ngOnInit(): void {
this.searchResultService.getSearchResultTable(122).subscribe( data => {
this.searchResult = data;
});
let t = this.searchResult;
}
}
这Model.SearchResult.RootObject
是一个复杂的对象,我在以下服务中由 json 生成它。
在所有示例中都描述了此方法......但在我的情况下this.searchResult
是undefined
. 我做错了什么?
更新
我还尝试以某种方式删除map
和更改服务方法:
getSearchResultTable(hash: number): Model.SearchResult.RootObject {
this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
.subscribe( data => {
this.searchResult = data;
});
return this.searchResult;
}
和组件方法,如:
ngOnInit(): void {
this.searchResult = this.searchResultService.getSearchResultTable(122);
}
服务获取下一个异常:
- ReferenceError:数据未定义
- 在评估(在 SearchResultService.getSearchResultTable 评估(webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts), :1:1)
- 在 SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:27:21)
- 在 SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:23 :54)
- 在 checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)
- 在 checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)
- 在 checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)
- 在 debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)
- 在 debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)
- 在 Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)
- 在 Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)
更新
在我的情况下,以下片段是正确的:
this.http.get<Model.SearchResult.RootObject>('http://someurl/api/SearchResult/123')
.subscribe( (data: Model.SearchResult.RootObject) => {
this.searchResult = data;
});
return this.searchResult;