简体   繁体   English

通过 Angular 与后端通信

[英]Communicate with backend through Angular

I have a developed a small library (js code) that I want to integrate with angular.我开发了一个小型库(js 代码),我想与 angular 集成。 the problem is that this library at a certain moment should make request ( ajax ) to push some results to the back-end.问题是这个库在某个时刻应该发出请求(ajax)将一些结果推送到后端。 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.抱歉,我对 angular 的了解很少,但是将前端收集的数据发送到后端的最佳方式是什么。

thanks谢谢

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):例如(示例是针对最新的 Angular 版本,以前的版本不支持HttpClient ,它只是Http 。我也使用toPromise ,它是可选的,如果需要,您可以处理observable ):

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));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM