JSONP call => ReferenceError : document is not def

2019-09-05 14:21发布

问题:

For my internship I'm asked to develop a mobile application based on this website (www.claroline.net). The technology I have to use is Nativescript combined with Angular 2. I managed to implement the login function so users of the website can now sign in on the app.

Then I have to be able to get the notifications of the website on the app. At the beginning I just want to display the notifications in a JSON array. I already have the url to get the JSON array (the get request works on the browser) but when I do that from the mobile application, I get a 500 error.

I heard then about JSONP which might help me solve my problem. Apparently there is few things to do : - import JSONP_PROVIDERS in the root component and bootstrap it - import Jsonp in the component you want to do the Jsonp call - add a callback parameter in the url

Am i missing anything ? Because even though I did all that, I get an error in the console :"ReferenceError : document is not defined" in some Javascript file which is weird because since I'm coding in Typescript, there are no variables called document.

回答1:

Here is the way to use JSONP support in Angular2.

After having registered JSONP_PROVIDERS when calling the bootstrap function:

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

bootstrap(AppComponent, [ JSONP_PROVIDERS ]);

You can then execute your request using an instance of the Jsonp class you injected from constructor:

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()
     });
  }
}

In your case, the c parameter could have another name but you need to set the JSONP_CALLBACK value in it.

See this plunkr: http://plnkr.co/edit/dqreqBL6kyNkR8Z2wgGR?p=preview