網站搜尋

javascript - Nativescript 與 angular 2 Http 服務


我正在通過 JavaScript 技術學習原生應用程式,並且我正在嘗試僅使用可用的 Pokémon API 建立一個簡單的應用程式。

我所做的

我創建了一個簡單的組件,用來列出一些寶可夢,這些寶可夢是來自 HTTP 回應的結果:

import {Component, OnInit} from '@angular/core';
import 'rxjs/Rx';
import {Http} from '@angular/http';

@Component({
  selector:'pokemon-list',
  templateUrl: 'components/pokemonList/pokemonList.html'
})
export default class PokemonList implements OnInit{

  pokemons: Array<any>;

  constructor(private http:Http){
    this.pokemons = [];
  }

  ngOnInit() {
    this.getRemote(); // I pass on here
  }

  getRemote(){
    this.http
      .get('https://pokeapi.co/api/v2/pokemon/') // Throws the weird error
      .map(res => res.json())
      .subscribe(res => {
        this.pokemons = res.results;
      });
  }
}

我的問題

當我啟動應用程式時,我遇到了一個奇怪的錯誤

Error in app.component.html:4:4 caused by: null is not an object (evaluating '_angular_platformBrowser.__platform_browser_private__.getDOM().getCookie')

我必須注意到,這個錯誤只會在我的 HTTP 請求中設置 getRemote 主體時發生。此外,當我在我的寶可夢清單中設置一個預設的寶可夢,且 API 返回的格式像 {name: 'Name', url: 'url'} 時,應用程式運作正常,寶可夢也能正確顯示。

如果我像以下這樣移除程式碼,應用程式就能運作。看起來我在那裡對 Http 模組漏掉了一些東西:

getRemote(){
    // App is running without the Http call
  }

注意:我正在使用 TS 2+,並且我已在當前模組中使用以下方式設置了 Http 模組:

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import {HttpModule} from '@angular/http';
import { NativeScriptModule } from "nativescript-angular/platform";
import PokemonList from './components/pokemonList/pokemonList.component';
import PokemonItem from './components/pokemonItem/pokemonItem.component';
import { AppComponent } from "./app.component";

@NgModule({
    declarations: [
      AppComponent,
      PokemonList,
      PokemonItem
    ],
    bootstrap: [AppComponent],
    imports: [
      NativeScriptModule,
      HttpModule
    ],
    schemas: [NO_ERRORS_SCHEMA]
})
export class AppModule { }

你知道我做錯了什麼嗎?

謝謝你的幫助

答案#1

在你的 NgModule 中,取代 HttpModule,你應該如這裡所示導入 NativeScript 包裝器 NativeScriptHttpModule https://github.com/NativeScript/nativescript-sdk-examples-ng/blob/master/app/http/http-examples.module.ts#L32

import { NativeScriptHttpModule } from "nativescript-angular/http";
...
@NgModule({
    imports: [
        NativeScriptHttpModule,
        ...

NativeScriptHttpModule 是 Angular 的 HttpModule 的 NativeScript 封裝,該模組聲明了所有基於 HTTP 的 Angular 服務...

在 NativeScript 中需要使用封裝器,因為 NativeScript 不「理解」Angular 中使用的 DOM 網頁特定屬性