我是 Angular 的新手。我想知道我是否可以使用服务向组件提供第三方 API,例如 leaflet 或 google maps?
我写了一个服务,其中我有 HTTP 请求传单 API URL,其中包含 javascript 函数。我正在将服务中的可观察对象返回到我的 map 组件。
这是服务:
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);
};
}
这是 map 组件:
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 GET 响应都是 JSON 字符串的假设,我期望收到一个 JSON 字符串,然后我想解析它以获得 javascript 函数。但是,在我使用订阅后不久,angular 给出了 HTTP 响应错误,因为它正在尝试 JSON 解析响应。
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 的理解有误,还是我的实现有误?请帮忙。
最佳答案
实际上,服务的使用是请求 API 将其数据提供给应用程序中的组件。不过,您尝试通过 HTTP GET 获取一个 javascript 文件。
因此,错误是 Unexpected token/in JSON
,因为它不是 JSON,而是 JS。
要加载外部 JS 文件,您可以按照有关如何使用 published libraries 的 Angular 指南进行操作。 .
leafletjs 的 npm 依赖项是:leaflet
和 @types/leaflet
。
关于angular - 如何使用 Angular 服务提供 leaflet 或 google maps 等第三方 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57721362/