简体   繁体   中英

Call Angular 5 service method from Vanilla JS JSONP callback

I'm calling the Flickr API from a service method. Flickr expects a global function expression to be available called jsonFlickrFeed , which I've placed in my app root index.html file immediately after the root component and before the closing body tag. I need to pass the response from the Vanilla JS callback back to the originating service.

It reaches the callback fine, but I'm really struggling to find any information how to get back to the service that's specifically relevant to Angular 5.

Here's my service

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/map';

import * as validResponse from './mock/valid.json';
import {FlickrItem} from "./flickr-item";
import {FlickrResponse} from "./flickr-response";

@Injectable()
export class FlickrService {
    private url: string = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json';
    private items: FlickrItem[];
    private response: FlickrResponse;

    constructor(private http: HttpClient) { }

    getValid() {
        // Return mock response
        // For development / debug use only
        // return validResponse;

        this.http.jsonp(this.url, 'jsonFlickrFeed').subscribe();
    };
}

As said here: Communication between angular 2 and pure javascript

You can define the callback inside the service using window:

@Injectable()
export class FlickrService {
...
  constructor(...) {
    window.jsonFlickrFeed = data => {
      // do something
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM