我已经在stackoverflow上尝试了许多关于修复此错误的命题,但现在我只需要问一下,因为我花了很多时间才真正无处可去。
我有这个简单的服务:
constructor(private http: Http, private tokenResolver: TokenResolver) {}
public getEventHistory(): Observable<heatmapElement[]> {
this.tokenResolver.getToken(true).subscribe(token => {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
headers.append('Content-Type', 'application/json');
this.result = this.http.get(this.restApi, new RequestOptions({headers: headers}))
.map((res: Response) => res.json());
});
return this.result as Observable<heatmapElement[]>;
}
我想使用以下方式获取数据:
public demoData: heatmapElement[] =[];
getEventHistory(): void {
this.eventHistoryService.getEventHistory()
.subscribe(data => this.demoData = data,);
}
这会产生一个我似乎无法解决的错误:
例外:未捕获(承诺):错误:导致http://localhost:5555/app/dashboard/dashboard.html:13:8错误:无法读取属性&#39;订阅&#39;未定义的 TypeError:无法读取属性&#39; subscribe&#39;未定义的
我非常感谢你的帮助, 谢谢
答案 0 :(得分:4)
奇怪,因为这可能是,在我的实例中,经过大量时间调试后,事实证明,我使用输出(@Output
)EventEmitter
属性来处理自定义事件,而Angular在模板上传递时,我无法识别我的属性或自定义事件属性:
e.g
<custom-component (keydownEvent)="someFunctoin()"></custom-component>
执行上述操作的问题是(就我的问题而言)(keydownEvent)
不是有效的事件处理程序,但是为什么它在开发中起作用,而不是在构建项目时。更奇怪的是,ng build --prod
不会发出任何错误或警告!
<强>解决方案强>
<custom-component keydown="someFunctoin()"></custom-component>
订阅者/订阅相关的错误在哪里?
好吧,正如你想象的那样,一个人订阅了EventEmitter
- 所以我猜这就是相关性的地方
答案 1 :(得分:2)
您无法在async call
方法之外返回subscribe
的结果。
如果您想从getEventHistory()
返回Observable,可以将subscribe
更改为map
或switchMap
。
public getEventHistory(): Observable<heatmapElement[]> {
return this.tokenResolver.getToken(true).switchMap(token => {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
headers.append('Content-Type', 'application/json');
return this.http.get(this.restApi, new RequestOptions({headers: headers}));
})
.map((res: Response) => res.json() as heatmapElement[]);
}