繁体   English   中英

angular2 http冲突InMemoryWebApiModule

[英]angular2 http conflict InMemoryWebApiModule

首先,我想知道URL错误,但是事实证明它是正确的。 这是github api作为我的测试URL

我把它放在chrome中,它返回了期望的结果。

其次,我想知道我的代码是否错误

constructor(private fb: FormBuilder, private _userService: UserService, private _http:Http) {

        this._http
            .get('https://api.github.com/search/repositories?q=ng2&page=1&per_page=10')
            .map((res: Response) => res.json())
            .catch((res: Response) => {
              return Observable.of({items: [], totalCount: 0, error: res.json()});
            })
            .subscribe(d => {
                console.log(d);
            })
    }

此代码始终会收到以下错误消息:

404-找不到集合“存储库”未找到

但是可以在我的Chrome浏览器中访问此URL。

而且我的代码找不到任何错误。

我终于找到了为什么会这样。

原因我将InMemoryWebApiModule添加到模块中。

但我不知道根本原因是什么

有人可以告诉我吗?

**

编辑:在提到InMemoryWebApiModule之前提供了此答案。

**

在您的UserService执行http请求:

export class UserService {

    constructor(private _http: Http) {  }

    getSomething() {
        return this._http.get('https://api.github.com/search/repositories?q=ng2&page=1&per_page=10')
         .map((res: Response) => res.json())
    }
}

并且在您的组件中,我建议您将方法放入ngOnInit而不是构造函数中:

ngOnInit() {
    this._userService.getSomething()
      .subscribe(d => console.log(d);
}

这是为什么的一些信息: OnInit和Constructor之间的区别

并记住在您的类中export class YourClass implements OnInit ... export class YourClass implements OnInit

我真的建议您看看“英雄巡回演唱会-Http”

编辑! 我检查了一下,并通过本文中对您的代码所做的更改,可以在Chrome和Firefox中使用! 见下文

在此处输入图片说明 在此处输入图片说明

还有一个正在工作的pl子... l子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM