嗨,我是 angular 5 的新手,我正在做一个演示项目,但我无法从一些 angular 参考书中在服务器上发布数据我得到了这个发送数据的逻辑,但它不起作用
let params = new HttpParams();
params.set('action','CATEGORY');
this.http.post(this.url,{params}).subscribe(res => console.log(res.text()));
它使用 GET 方法。
angular 提供HttpClient
使用 http 方法,您应该像这样导入:
import {HttpClient} from "@angular/common/http";
然后使用服务与服务器联系
您可以通过ng g service yourservice
命令创建服务
在您的构造函数中准备好这样的 httpclient 实例,并在我们需要时编写一个与服务器联系的函数:
export class yourService {
constructor(private http: HttpClient) {
}
getData(data) {
return this.http.post("your destinition url", data)
}
}
并且在您喜欢的每个组件中,您都可以通过服务调用该函数
export class SimpleComponent implements OnInit{
constructor(private _service: yourService) {
}
ngOnInit() {
let data = {id: 1} // everthing you need pass in request this is just a example
this._service.getData(data).subscribe(data => {
console.log(data)
}
}
数据包含服务器响应和您的结果
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句