簡體   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