基础用法
app.module.ts
import { HttpClientModule } from '@angular/common/http'
@NgModule({
imports: [
HttpClientModule
]
})
export class AppModule { }
app.component.ts
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angular-base';
constructor(private http: HttpClient) {}
loadData() {
this.http.get(url).subscribe((res: any) => {
console.log(res)
})
}
}
封装到service服务中
全局配置
src/app/config.ts
export const baseUrl = "http://localhost:3000"
接口
demo.type.ts
export interface Todo {
id: number,
name: string,
done: boolean
}
创建一个服务
一般在服务中返回数据,在组件中subscribe()
service-demo.service.ts
import { Injectable } from '@angular/core';
// 导入HttpClient
import { HttpClient } from '@angular/common/http'
// 导入配置
import { baseUrl } from '../config'
import { Todo } from './demo.type';
@Injectable({
providedIn: 'root'
})
export class ServiceDemoService {
constructor(private http: HttpClient) { }
serviceMethod() {
return "这是service中的方法"
}
loadData() {
const url = `${baseUrl}/todos`
return this.http.get<Todo[]>(url, {
// 获取完整响应体
// observe: 'response'
// headers: {
// Authorization: `Bearer ${token}`
// }
})
}
}
在组件中调用
http-demo.component.ts
import { Component, OnInit } from '@angular/core';
import { ServiceDemoService } from '../service-demo.service';
import { Todo } from '../demo.type';
@Component({
selector: 'app-http-demo',
templateUrl: './http-demo.component.html',
styleUrls: ['./http-demo.component.scss']
})
export class HttpDemoComponent implements OnInit {
constructor(private sdService: ServiceDemoService) { }
ngOnInit(): void {
}
todoList: Todo[] = []
loadData() {
this.sdService.loadData().subscribe((res: Todo[]) => {
console.log(res)
// this.todoList = res
// 优化:拷贝后赋值
this.todos = [...todos]
}, err => {
console.log(err)
})
}
}
GET / POST / DELETE / PUT
通用方法
var option = { body: user };
this.http.request("post", "http://localhost/api/v1/sys/login", option).subscribe(
(res: any) => {
console.log(res)
if (res.code == '200') {
this.isLogin = true
}
x.next(res);
x.complete();
},
(y) => {
x.error(y);
x.complete();
},
() => {
x.complete();
}
)
POST
this.http.post("http://localhost/api/v1/sys/login", {
"username": user.username,
"password": user.password
}).subscribe(
(res: any) => {
console.log(res)
if (res.code == '200') {
this.isLogin = true
}
x.next(res);
x.complete();
},
(y) => {
x.error(y);
x.complete();
},
() => {
x.complete();
}
)