第一,首先是Http文件负责最主要的请求:
import {Injectable} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Config} from './config';
import {Router} from '@angular/router';
@Injectable()
export class Http {
constructor(public msg: NzMessageService, public httpClient: HttpClient, private router: Router) {
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'token': localStorage.getItem('token')
})
};
this.httpClient.post( Config.API_URL + url, data, httpOptions,
).subscribe((result: ValueObject) => {
console.log(result);
if (result.status == -2){
this.msg.error('token过期,请重新登录');
this.router.navigate(['login']);
}
return callbackFun(result);
}, error => {
callbackFun(error);
});
}
}
interface ValueObject {
status?: number
}
其次是service文件:
import {Injectable} from '@angular/core';
import {Http} from './http';
/**
* 用户登录服务
*/
import {Http} from './http';
@Injectable()
export class Service {
constructor(private http: Http) {}
// 分类
test(data, callbackFun) {
this.http.request('xxx/xxx',
data
, callbackFun);
}
}
第三才是业务:
import {Service} from '../service/service';
export class Xxxx implements OnInit {
constructor(private service: Service) {
this.getAllData();
}
getAllData(){
this.service.getAllProduct(null, (result) => {
console.log(result);
});
}
}
图片上传:
const file = Imageinput.files[0];
const data: FormData = new FormData();
data.append('file', file, file.name);
const header = new Headers();
header.append('Accept', 'application/json');
this.httpClient.post(Config.API_URL + 'xxx', data)
.subscribe((res) => {
console.log(res);
});
网友评论