我对角质很陌生。我想知道是否可以使用服务向组件提供第三方API,如传单或谷歌地图?
我编写了一个服务,其中我有HTTP请求传单API URL,其中包含javascript函数。我将可观察到的从服务返回到我的地图组件。
以下是服务:
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class LeafletService {
private Lurl = "https://unpkg.com/leaflet@1.5.1/dist/leaflet.js";
httpHeaders = new HttpHeaders({'Content-type': 'application/json'});
urlText: string;
constructor(private http: HttpClient) {}
getL():Observable<any>{
return this.http.get(this.Lurl);
};
}下面是地图组件:
import { Component, OnInit } from '@angular/core';
import {LeafletService} from '../../services/leaflet.service';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css'],
providers: [LeafletService]
})
export class MapComponent implements OnInit {
L: any;
constructor(private llService: LeafletService) {}
ngOnInit() {
this.getL();
}
getL(): void{
this.llService.getL().subscribe(
data => {
console.log(data);
this.L = data;
return this.L;
},
error => {
console.log(error);
}
);
}
}基于所有HTTP响应都是JSON字符串的假设,我希望接收一个JSON字符串,然后解析它以获得javascript函数。然而,在我使用订阅之后不久,angular就给出了一个HTTP响应错误,因为它试图解析响应。
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://unpkg.com/leaflet@1.5.1/dist/leaflet.js", ok: false, …}
error: {error: SyntaxError: Unexpected token / in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "/* @preserve↵ * Leaflet 1.5.1+build.2e3e0ff, a JS …function(){return window.L=zn,this},window.L=t});"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
__proto__: HttpResponseBase我对使用服务提供API的理解是错误的还是我的实现是错误的?请帮帮忙。
发布于 2019-08-30 06:23:43
实际上,服务的使用是请求app将其数据提供给应用程序中的组件。不过,您试图获得一个javascript文件。
因此,错误是Unexpected token / in JSON,因为它不是JSON,而是JS。
要加载外部JS文件,您可以遵循以下关于如何使用出版图书馆的角度指南。
传单的npm依赖项是:leaflet和@types/leaflet。
https://stackoverflow.com/questions/57721362
复制相似问题