我正在使用角度2前端,它使用Spring引导的休息API。在angular项目中,我有文件globals.ts,它包含可由所有组件访问的全局开发变量。在我的前端,我有基于Rest API搜索数据的组件(可以是本地或远程API依赖于global.ts)。
globals.ts
export class Globals {
//localhost or 21.222.54.400:8090
public static get server(): string { return 'http://21.222.54.400:8090'; }}
如果我将服务器指定为localhost并且它使用从我的本地spring应用程序运行的API,它可以正常工作。但如果我将其更改为远程API,则返回:
error_handler.js:51 TypeError: Cannot read property 'filter' of undefined
at SearchPipe.transform (search.pipe.ts:11)
at view_utils.js:159
at _View_SearchpopupComponent0.detectChangesInternal (SearchpopupComponent.ngfactory.js:96)
at _View_SearchpopupComponent0.AppView.detectChanges (view.js:272)
at _View_MidrouteComponent0.AppView.detectViewChildrenChanges (view.js:298)
at _View_MidrouteComponent0.detectChangesInternal (MidrouteComponent.ngfactory.js:85)
at _View_MidrouteComponent0.AppView.detectChanges (view.js:272)
at _View_MidrouteComponent_Host0.AppView.detectViewChildrenChanges (view.js:298)
at _View_MidrouteComponent_Host0.AppView.detectChangesInternal (view.js:283)
at _View_MidrouteComponent_Host0.AppView.detectChanges (view.js:272)ErrorHandler.handleError @ error_handler.js:51
zone.js:140未捕获的TypeError:无法读取未定义的属性“过滤器”(...)
这很奇怪,因为我可以使用rest API来实现另一个重要性,除了pipe。
这是我的search.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(service: any, term: any): any {
if (term=== undefined) return null;
return service.filter(function(service){
return service.product_name.toLowerCase().includes(term.toLowerCase());
})
}
}
这是我的search.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Home } from '../home/home';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import {Globals} from "../globals";
@Injectable()
export class SearchService {
constructor (private http: Http) {}
private Url = Globals.server+'/product?size=2000'; // URL to web API
getService (){
return this.http.get(this.Url)
.map(res => <Home[]> res.json())
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
在我的组件中我称之为:
getHomes() {
this.homeService.getService()
.subscribe(
services => this.services = services.content,
error => this.errorMessage = <any>error);
}
在模板中我打电话给{{ service.product_name }}
所有帮助都将受到高度尊重。感谢
答案 0 :(得分:0)
我明白为什么会发生这种情况,这是因为从远程API获取数据需要时间来完成。我试着在访问API之前等待一段时间,然后一切都像它使用的那样运行。