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

时间:2017-09-02 23:37:21

标签: angular http angular2-http

我想将一些数据发送到服务器并在我的onSelected方法中等待它的回答。你知道怎么用Angular使用http吗?这是我的代码:

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

2 个答案:

答案 0 :(得分:0)

试试这个,

 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)然后执行任何操作,以通知用户成功。

答案 1 :(得分:-1)

如果您想通过HTTP进行通信,可以在角度中使用Http类。

示例:

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

link。它是我用来通过JSON向服务器发送事件和从服务器发送事件的服务。

编辑:我认为创建用于制作这些HTTP请求的附加服务非常有用,因此您可以清楚地了解您的服务。也许你可以用另一种方式重复使用它:)