-3

I have a developed a small library (js code) that I want to integrate with angular. the problem is that this library at a certain moment should make request ( ajax ) to push some results to the back-end. How can I make that in angular ? should I develop directives to support binding ? Sorry I have small knowlege in angular but whats the best way to send data collected by the front end to backend.

thanks

zahma
  • 412
  • 4
  • 14
  • Possible duplicate of [What is the best practice for making an AJAX call in Angular.js?](https://stackoverflow.com/questions/17646034/what-is-the-best-practice-for-making-an-ajax-call-in-angular-js) – Liam Feb 15 '18 at 10:26
  • If this post is not mess up, it's not the same framework (angular =/= angular.js) – wilovent Feb 15 '18 at 10:29
  • @Liam here I'm speaking about Angular framework and not angularJs – zahma Feb 15 '18 at 12:04

1 Answers1

1

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));
  }
}
P.S.
  • 15,970
  • 14
  • 62
  • 86