异常:未捕获( promise ):错误:http://localhost:3000/app/search/results/templates/search-results.component.html:88:58 中出现错误原因:无法读取未定义的属性“长度” 类型错误:无法读取未定义的属性“长度”
所以,问题是 POST 方法似乎工作得很好。 do() 记录了来自服务器的正确预期响应,但在 SearchService 中的 getSearchResults() 实现和 SearchResultsComponent 中的函数调用之间的某个地方出现了故障。 _searchResults 永远不会更新为任何值。
search.service.ts
getSearchResults(numberOfResults: number, offset: number, sortProperties?: ISort): Observable<ISearchResult[]>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let searchParams = localStorage.getItem("savedSearchParameters");
return this._http.post(this._baseUrl + "customer", searchParams, options)
.do(r => console.log(r))
.map((r: Response) => r.json().data as ISearchResult[]);
}
search-results.component.ts
private _searchResults: ISearchResult[];
this._searchService.getSearchResults(this.numResultsToFetch(), this._resultOffset)
.subscribe((data: ISearchResult[]) => this._searchResults = data);
search-results.template.html
<results-table
*ngIf="_searchResults.length > 0"
(sortEvent)="onSort($event)"
[resultsPerPage]="_resultSettings.resultsPerPage"
[pageNumber]="_pageNumber"
[resultOffset]="_resultOffset"
[columnMapping]="_columnMapping"
[totalPages]="_totalPages"
[columnsToBeDisplayed]="_resultSettings.columnsToBeDisplayed"
[displayData]="_searchResults"></results-table>
最佳答案
您需要将 private _searchResults: ISearchResult[];
设置为空数组,因为它在开始时未定义,因为您的请求是异步的,因此组件无法在尚未完成的内容上调用 .length定义的。
应该是:private _searchResults: ISearchResult[] = []
关于javascript - Angular 2 - API 请求未返回 Observable,错误 : undefined has no property 'length' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953654/