完整的代码, 可以复制引用
// 创建服务命令
// 使用Angular CLI创建服务
// npm ng g s service
在app.module.js中导入和提供服务
import { ServiceService } from './service/service.service';
// 在NgModule的providers数组中注册服务
providers: [ServiceService],
Service文件内容
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ServiceService {
private homeUrl = 'http://a.itying.com/api/productlist';
constructor(public http: HttpClient) { }
// GET请求
get() {
return new Promise((resolve, reject) => {
this.http.get(this.homeUrl).subscribe((res) => {
resolve(res);
});
});
}
// POST请求
public post(url: string, json: any) {
const api = this.domian + url;
const headers = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return new Promise((resolve, reject) => {
this.http.post(api, json, headers).subscribe(res => {
resolve(res);
}, (error) => {
reject(error);
});
});
}
}
在组件中导入服务
import { ServiceService } from '../../service/service.service';
// 然后在组件的构造函数中注入服务,并在组件的方法中使用服务的方法