我正在通过 javascript 技术学习 native 应用程序,并且我正在尝试使用仅可用的 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 正文时,才会发生此错误。此外,当我在我的口袋妖怪列表中设置默认口袋妖怪时,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 { }
知道我做错了什么吗?
感谢您的帮助
最佳答案
在您的 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 is a NativeScript wrapper of Angular’s HttpModule, a module that declares all of Angular’s HTTP-based services...
需要在 NativeScript 中使用包装器,因为 NativeScript 无法“理解”Angular 中使用的 DOM Web 特定属性
关于javascript - Nativescript 和 Angular 2 Http 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41217475/