简体   繁体   English

angular2 http冲突InMemoryWebApiModule

[英]angular2 http conflict InMemoryWebApiModule

First I wonder the URL is wrong, but turn out it is right. 首先,我想知道URL错误,但是事实证明它是正确的。 here is github api as my test url 这是github api作为我的测试URL

I put it in chrome, it return desire result. 我把它放在chrome中,它返回了期望的结果。

Second I wonder if my code is wrong 其次,我想知道我的代码是否错误

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);
            })
    }

this code always get this error message: 此代码始终会收到以下错误消息:

404 - Not Found Collection 'repositories' not found 404-找不到集合“存储库”未找到

But this URL can be accessed in my chrome. 但是可以在我的Chrome浏览器中访问此URL。

and I can't find any wrong with my code. 而且我的代码找不到任何错误。

I finally found why this happened. 我终于找到了为什么会这样。

Cause I add InMemoryWebApiModule into my module. 原因我将InMemoryWebApiModule添加到模块中。

but I don't know what is root cause here 但我不知道根本原因是什么

somebody could tell me? 有人可以告诉我吗?

** **

EDIT: this answer was provided before there was a mention of InMemoryWebApiModule. 编辑:在提到InMemoryWebApiModule之前提供了此答案。

** **

Do the http-request in your UserService : 在您的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())
    }
}

And in your component I would suggest you put your method in ngOnInit rather than the constructor: 并且在您的组件中,我建议您将方法放入ngOnInit而不是构造函数中:

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

Here is some info why: Difference between OnInit and Constructor 这是为什么的一些信息: OnInit和Constructor之间的区别

And remember to implement the OnInit in your class... export class YourClass implements OnInit 并记住在您的类中export class YourClass implements OnInit ... export class YourClass implements OnInit

I really suggest you take a look at Tour Of Heroes - Http 我真的建议您看看“英雄巡回演唱会-Http”

EDIT! 编辑! I checked, and with the changes I did to your code here in this post, work both in Chrome and Firefox! 我检查了一下,并通过本文中对您的代码所做的更改,可以在Chrome和Firefox中使用! See below 见下文

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

And a working plunker here... Plunk 还有一个正在工作的pl子... l子

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

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