导入AngularModule

在 app.module.ts 中引入 HttpClientModule、HttpClientJsonpModule 并注入

1
2
3
4
5
6
7
import {HttpClientModule,HttpClientJsonpModule} from '@angular/common/http';

imports: [
BrowserModule,
HttpClientModule,
HttpClientJsonpModule,
...

needed-service.ts

在用到的地方引入 HttpClient 并在构造函数声明

1
2
3
4
5
6
7
8
9
import { HttpClient } from '@angular/common/http';

constructor(
private http: HttpClient,
) { }

demo(): Observable<any> {
return this.http.jsonp(`http://api.wipmania.com/jsonp`, 'callback')
}

needed-component.ts

jsonp 请求数据

1
2
3
4
5
6
7
8
9
import { needed-service } from 'xxx';

constructor(
private needService: NeedService,
) { }

demo() {
this.neededService.demo().subscribe( res => {console.log(res);})
}