使用 http 将数据发送到服务器并等待答案

Send data to server and wait an answer using http

我想向服务器发送一些数据并在我的 onSelected 方法中等待它的答复。您知道如何使用 http 对 Angular 执行此操作吗?这是我的代码:

import {Http, Headers} from '@angular/http';
import { CompleterService, CompleterData } from 'ng2-completer';
import { Logger } from '../../app/logger.service'
import { MapController } from './map.service'
import { BrowserModule} from '@angular/platform-browser';

export class TService {
    logger:Logger = new Logger(this.constructor.name);

    protected mapController:MapController;
    protected searchStr: string;
    protected dataService: any;
    private placeHolder = "select a field";

protected searchData = [
        { name: 'A',         desc: '1'},
        { name: 'B',         desc: '2'},
        { name: 'C',  desc: '3'}
      ];

constructor(private completerService: CompleterService, private Http:Http) {
        this.logger.log("TService()");
        this.dataService = completerService.local(this.searchData, 'name,desc', 'name')
        .descriptionField('desc')     
    }





        public onSelected(event:any) {
            this.logger.log(event);
            //I want to send to the server the object "Event" using a post after clicking on a button
            console.log(event);
         //http code
         
         //return ok if object received by the server           
            
        }
}

如果您想通过 HTTP 进行通信,可以使用 angular 中的 Http class。

示例:

this.http.post( 'URL', JSON.stringify( message)).map( ( res: Response ) => res.json() ).subscribe( ( response: Response ) => { /* do something with response */ } );

看到这个 link。这是我用来通过 JSON.

向服务器发送事件和从服务器发送事件的服务

编辑:我认为为发出这些 HTTP 请求创建一个附加服务很有用,这样您就可以清楚地划分您的服务。也许你可以用另一种方式重用它:)

试试这个,

 public onSelected(event:any) {
        this.logger.log(event);
        this.Http.post('your-post-url', JSON.stringify(event)) 
        .subscribe( response => {
           if(response.status === 200 ) {
             // Do something with the message, after success
           }
         })     
    }

subscribe 方法只会在收到服务器响应时执行,然后你可以检查它是否是成功消息(状态码 200),然后做任何你想做的事情,通知用户成功.