在Angular 2中,我如何根据表单模型向服务器发送数据。在某些情况下,我可能会通过单击addMore按钮添加更多行。
enter image description here
发布于 2016-09-28 08:22:40
首先需要导入HttpModule,如果要发送json_encoded数据,还需要导入JsonpModule。您可以从@angular/http导入这两个模块,并将其作为@NgModule中的导入添加到app.module.ts文件中
app.module.ts:
import { HttpModule, JsonpModule } from '@angular/http';
@NgModule({
imports: [
...,
HttpModule,
JsonpModule
],
bootstrap: [AppComponent]
})下一步是创建一个处理Http请求的服务。您将需要从rxjs包中导入Observable对象和map方法来处理响应。此外,如果您想通过post Http请求发布数据,则需要导入HTTP、Response、Header和RequestOptions对象(所有对象都是@angular/http格式的。在服务中,您可以设置可以从组件访问的函数,并使用它将数据发送到服务器并捕获您可以订阅的响应。
http.service.ts:
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
@Injectable()
export class HttpService {
private _url: string = "http://example.com"; // Url which handles JSON encoded data
constructor(private _http: Http) {} // Injecting the Http Service
sendData(data): Observable<Object> {
let encoded_data = JSON.stringify({ data });
let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
let options = new RequestOptions({ headers: headers });
return this._http.post(encoded_data, this._url, options).map(
(res: Response) => res.json() || {}
);
}在component中,您需要导入服务并使用刚刚创建的方法。您也可以订阅此方法来获取响应。
example.component.ts:
import { Component, OnInit } from '@angular/core';
import { HttpService } from 'http.service';
@Component({
...
})
export class ExampleComponent implements OnInit {
constructor(private _httpService: HttpService) {}
ngOnInit() {}
sendDataToServer(dataFromForm) {
this._httpService.sendData(dataFromForm).subscribe(
response => console.log(response), // success
error => console.log(error), // error
() => console.log('completed') // complete
}
}欲了解更多信息,请访问HTTP Client
https://stackoverflow.com/questions/39735866
复制相似问题