【问题标题】:404 error with .get on angular2.get 在 angular2 上出现 404 错误
【发布时间】:2017-04-18 14:54:37
【问题描述】:

我是 angular2 新手,我尝试基于 angular2 快速入门项目开发自己的应用程序。

所以问题是:当我尝试使用真正的 API 来获取我的数据时,我总是遇到 404 错误(无论 API url 是什么)。

这是我的服务代码:

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { League } from './league';
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class LeagueService {

 private headers = new Headers({'X-Mashape-Key': 'MY_API_KEY'});
 private leaguesUrl = 'https://sportsop-soccer-sports-open-data-v1.p.mashape.com/v1/leagues';

 constructor(private http: Http) {}

 getLeagues(): Observable<League[]> {
    return this.http.get(this.leaguesUrl,{headers: this.headers})
                .map(this.extractData)
                .catch(this.handleError);
 }

 private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
 }

  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

handleError 方法给我发回了这个:“Not Found Collection 'leagues' not found”。我已经尝试过 promise 和 observable。

我知道这个 API 可用并且不会发回 404。

你能告诉我这里发生了什么吗? :-)

谢谢!

【问题讨论】:

  • 浏览器控制台报告什么?能否请您添加确切的错误消息?
  • 404 - Not Found Collection 'leagues' not found League.service.ts:36
  • 尝试通过 Postman 发送相同的请求。
  • 搜索“未找到集合”仅显示提及 InMemoryWebAPI。你用InMemoryWebAPI吗?你能在 Plunker 中重现吗?
  • 不知何故,我怀疑 @banibanc 正在使用他自己的项目,基于来自 angular.io/docs/ts/latest/guide/… 的 plunker 中的代码和配置,它确实在内存 web api 中使用。只是一个想法。如果你是 banibanc,那可能就是你的配置问题。

标签: angular


【解决方案1】:

尝试将内容类型添加到构造函数的标题中。

headers.append('Content-Type', 'application/json');

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2017-01-23
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多