【问题标题】:JSONP call => ReferenceError : document is not definedJSONP 调用 => ReferenceError:文档未定义
【发布时间】:2016-06-23 22:14:45
【问题描述】:

在我的实习中,我被要求基于这个网站 (www.claroline.net) 开发一个移动应用程序。我必须使用的技术是 Nativescript 结合 Angular 2。我设法实现了登录功能,因此网站的用户现在可以在应用程序上登录。

然后我必须能够在应用程序上获得网站的通知。一开始我只想在 JSON 数组中显示通知。我已经有了获取 JSON 数组的 url(get 请求在浏览器上工作),但是当我从移动应用程序执行此操作时,我收到 500 错误。

然后我听说 JSONP 可能会帮助我解决我的问题。显然有几件事要做: - 在根组件中导入 JSONP_PROVIDERS 并引导它 - 在要调用 Jsonp 的组件中导入 Jsonp - 在url中添加回调参数

我错过了什么吗?因为即使我做了所有这些,我在控制台中收到一个错误:“ReferenceError:document is not defined” in some Javascript file 这很奇怪,因为因为我在 Typescript 中编码,所以没有称为 document 的变量。

【问题讨论】:

  • Status 500 表示服务器有问题(或格式错误的请求)。 JSONP 在这里无济于事。

标签: typescript jsonp angular


【解决方案1】:

这是在 Angular2 中使用 JSONP 支持的方法。

在调用bootstrap函数时注册JSONP_PROVIDERS后:

import {bootstrap} from 'angular2/platform/browser'
import {JSONP_PROVIDERS} from 'angular2/http'
import {AppComponent} from './app.component'

bootstrap(AppComponent, [ JSONP_PROVIDERS ]);

然后您可以使用从构造函数注入的Jsonp 类的实例来执行您的请求:

import {Component} from 'angular2/core';
import {Jsonp} from 'angular2/http';

@Component({
  selector: 'my-app',
  template: `
    <div>
      Result: {{result | json}}
    </div>
  `
})
export class AppComponent {
  constructor(jsonp:Jsonp) {
    var url = 'https://...&c=JSONP_CALLBACK';
    jsonp.request(url, { method: 'Get' })
     .subscribe((res) => {
       this.result = res.json()
     });
  }
}

在您的情况下,c 参数可以有另一个名称,但您需要在其中设置 JSONP_CALLBACK 值。

看到这个 plunkr:http://plnkr.co/edit/dqreqBL6kyNkR8Z2wgGR?p=preview

【讨论】:

  • 在我的情况下如何知道 c 参数的名称?
  • 你想打哪个电话?
  • 你可以查看这个 plunker plnkr.co/edit/W5bWKL7GJrQLdR1WTsyJ?p=info(user.service.ts 中的最后一个方法)
  • 谢谢! Config.apiUrl 你有什么?
  • 您可以尝试使用 curl 执行您的请求吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
相关资源
最近更新 更多