从Vanilla JS JSONP回调中调用Angular 5服务方法

问题描述 投票:0回答:1

我从服务方法调用Flickr API。 Flickr期望一个名为jsonFlickrFeed的全局函数表达式可用,我已将其放在我的应用程序根目录index.html文件中,紧接在根组件之后和结束正文标记之前。我需要将Vanilla JS回调的响应传递回原始服务。

它回调很好,但我真的很难找到任何信息如何回到与Angular 5特别相关的服务。

这是我的服务

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();
    };
}
javascript angular jsonp angular5
1个回答
1
投票

如上所述:Communication between angular 2 and pure javascript

您可以使用窗口在服务中定义回调:

@Injectable()
export class FlickrService {
...
  constructor(...) {
    window.jsonFlickrFeed = data => {
      // do something
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.