【问题标题】:Nativescript and angular 2 Http serviceNativescript 和 Angular 2 Http 服务
【发布时间】:2025-12-27 22:45:14
【问题描述】:

我正在通过 javascript 技术学习本机应用程序,并且我正在尝试使用仅可用的 pokemon 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 主体时才会发生此错误。此外,当我在我的 pokemon 列表中设置一个默认 pokemon,API 结果格式如 {name: 'Name', url: 'url} 时,应用程序正在运行并且 pokemon 显示良好。

如果我删除如下代码,则该应用程序正在运行。看来我在那里缺少 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 { }

知道我做错了什么吗?

感谢您的帮助

【问题讨论】:

    标签: javascript angular typescript nativescript


    【解决方案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 的 NativeScript 包装器 HttpModule,一个声明所有 Angular 的基于 HTTP 的模块 服务...

    需要在 NativeScript 中使用包装器,因为 NativeScript 不“理解”Angular 中使用的 DOM Web 特定属性

    【讨论】: