typescript - 使用 RequestOptions 的 Angular http 获取失败
我有两个函数,一个可以正常工作,另一个给我这个 404 错误:
/get[object%20Object] 404(未找到)
函数 getNews 给了我那个错误,我使用 console.log 查看两个函数的值,结果是一样的:this.newId="1",所以我用一个字符串调用两个方法,使用 "New" 的 ID,但它只对 onVote 方法有效。
为什么在 getNews 的情况下我在请求中得到的是一个对象,而在 onVote 中我得到的是 id?
这是 component.ts 文件:
export class NewDetailsComponent implements OnInit
{
params = new URLSearchParams();
options = new RequestOptions({ withCredentials: true });
oneNew: New;
newId: string;
constructor(public http: Http, private activatedRoute: ActivatedRoute)
{ }
ngOnInit()
{
this.activatedRoute.params.subscribe(params =>
{
this.newId = params['id']
});
this.getNews(this.newId)
}
getNews(id: string)
{
this.params.set('id', id)
this.options.search = this.params
this.http
.get(ApiConfig.API_URL + 'news/get' + this.options)
.toPromise()
.then(response =>
{
this.oneNew = <New>response.json()
})
}
onVote(id: string)
{
this.params.set('id', id.toString())
this.options.search = this.params
this.http
.get(ApiConfig.API_URL + 'news/Vote', this.options)
.toPromise()
}
答案#1
你的获取使用的是 + 而不是 , 来添加选项:
getNews(id: string)
{
this.params.set('id', id)
this.options.search = this.params
this.http
.get(ApiConfig.API_URL + 'news/get', this.options)
.toPromise()
.then(response =>
{
this.oneNew = <New>response.json()
})
}
应该解决这个问题
