【发布时间】:2016-03-12 23:02:56
【问题描述】:
我想使用 REST api,它在 Angular 2 的另一台服务器上运行。
在documentation they provide an example 如何使用 observables 做到这一点:
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Hero} from './hero';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HeroService {
constructor (private http: Http) {}
private _heroesUrl = 'http://someserver:8080/heroes'; // URL to external web api
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => <Hero[]> res.json().data)
.catch(this.handleError);
}
private handleError (error: Response) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
请注意,我只是更改了 _heroesUrl 以使用外部 api,其余的与文档中的完全相同。
不幸的是,它会给我一个错误:
EXCEPTION: TypeError: this.http.get(...).map is not a function in [null]
显然它不会得到任何数据。如何操作 http 标头以便处理 CORS 请求?
编辑 1
- 我通过在后端相应地设置标头解决了 CORS 问题。
-
我添加了 map & observables 的导入:
导入 'rxjs/add/operator/map' 导入'rxjs/Rx';
现在以前的错误消失了,但是,我的控制台中弹出了一个新错误:
Uncaught (in promise) TypeError: object is not a constructor(…) [undefined:1]
当我单击异常以在 chrome 开发控制台中查看它的来源时,它会打开一个新的空选项卡...现在有点卡在这里
【问题讨论】:
-
CORS 可以通过在rest serverstackoverflow.com/questions/35957751/…添加http头来处理@
-
@Gary 谢谢,不知道。我在我的 nancyfx 后端添加了标题
-
@AngelAngel 谢谢,我添加了导入,现在出现新错误,请参阅我的编辑
-
@Ronin 删除 .catch() 会发生什么?尝试将 catch 与 subscribe 一起使用
标签: angular rest typescript