角jsonp调用 [英] Angular jsonp calls
问题描述
如何通过新的Angular HttpClientModule进行jsonp调用?
How do you make jsonp calls via the new Angular HttpClientModule?
我看到有一个HttpClient.jsonp方法,但是从文档中对我来说,设置HttpClientJsonpModule拦截器并不十分清楚.我不确定JsonpCallbackContext应该来自哪里?
I see there's an HttpClient.jsonp method but setting up a HttpClientJsonpModule interceptor isn't very clear to me from the documentation. I'm not sure where JsonpCallbackContext should come from?
https://angular.io/api/common/http/HttpClientJsonpModule
仅添加HttpClientJsonpModule会导致以下错误-
Just adding HttpClientJsonpModule leads to the following error -
Refused to execute script because its MIME type ('application/json') is not executable
推荐答案
为了使JSONP在Angular(v4.3 +)中工作,您需要将其添加到AppModule
In order to get JSONP to work in Angular (v4.3+) you need to add this to your AppModule
import { HttpClientJsonpModule } from '@angular/common/http';
@NgModule({
imports: [ BrowserModule, HttpClientJsonpModule ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
然后在您的服务或组件中
Then in your service or component
private WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php';
const url = searchUrl(term, this.WIKIPEDIA_URL);
this.http.jsonp(url, 'callback')
function searchUrl(term, base) {
let params = new HttpParams()
.append('action', 'opensearch')
.append('search', encodeURIComponent(term))
.append('format', 'json');
return `${base}?${params.toString()}`;
}
根据需要添加了一些参数,以使Wikipedia搜索正常工作.
Added some params as needed for Wikipedia search to work.
这篇关于角jsonp调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!