The best way to interact with backend is to use services. For example (the example is for the latest Angular version, previous versions doesn't support HttpClient
, it's just Http
. I also use toPromise
, it's optional, you can deal with observable
if you want):
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class YourService {
constructor(
private _http: HttpClient
) { }
public sendDataToServer(data: any): Promise<any> {
return this._http.post(http://fakehost/fakeurl, data)
.toPromise()
.catch(err => console.error(err));
}
And inside your component:
import { Component } from '@angular/core';
import { YourService } from '../../core/your-service.service';
@Component({
selector: 'your-component',
templateUrl: './your-component.component.html',
styles: [``]
})
export class SignUpComponent {
constructor(private _yourService: YourService) {
this.ApiCall();
}
public ApiCall(): void {
this._yourService.sendDataToServer("any data here")
.then(response => {
console.log("Response:", response);
})
.catch(err => console.error(err));
}
}