Angular有自己的HTTP库,我们可以用它来调用外部API。 在老的版本中HTTP模块位于@angular/http ,新的版本已经迁移到@angular/common/http
。
导入http模块
在app.module.ts
中,引入http模块
import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http';
然后注入模块
@NgModule({
declarations: [
AppComponent,
SimpleHttpComponent
],
imports: [
HttpClientModule,
HttpClientJsonpModule
],
providers: [{ provide: NZ_I18N, useValue: zh_CN }],
bootstrap: [AppComponent]
})
新建一个测试模块
执行以下命令创建模块
ng g c SimpleHttp
引入HttpClient
在新建模块的ts文件中,引入HttpClient
模块,并在构造函数中注入。
import { HttpClient } from '@angular/common/http';
private httpClient: HttpClient;
constructor(httpClient: HttpClient) {
this.httpClient = httpClient
}
使用
let url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1"
this.httpClient.get(url).subscribe((response) => {
console.log(response);
}, (err) => {
console.warn(err)
})
其他
除了get
方法,还有我们常用的post
、put
、delete
、request
等方法。
传递参数
当然我们可以给后台传递参数的,这里我模拟一个login请求。post
处理请求时,我们可能需要传递头部还有返回值类型信息,不然会报错。
后台用Spring Boot模拟登陆
@RestController
public class LoginController {
@PostMapping("login")
@CrossOrigin
public String Login(@RequestBody LoginEntity loginEntity){
LoginEntity entity = loginEntity;
return "success";
}
}
前端完整调用代码
import { Component, OnInit } from '@angular/core';
import { HttpClient ,HttpHeaders} from '@angular/common/http';
@Component({
selector: 'app-simple-http',
templateUrl: './simple-http.component.html',
styleUrls: ['./simple-http.component.css']
})
export class SimpleHttpComponent implements OnInit {
private httpClient: HttpClient;
private headers = new HttpHeaders({'Content-Type': 'application/json'});
constructor(httpClient: HttpClient) {
this.httpClient = httpClient
}
ngOnInit(): void {
let url = "http://localhost:8080/login"
let param = {
userName:'张三'
}
this.httpClient.post(url,param,{headers:this.headers,responseType:'text'}).subscribe(function(response) {
console.log('我取到数据了:'+response)
}, function(err){
debugger
console.log('报错了:'+err)
})
}
}
评论 (0)