如何将JSON对象发布到服务器?

时间:2018-04-06 19:34:03

标签: angular mongodb http-post

我无法找到解决问题的方法,但请随时与我联系。这是完整的sign-up.component.ts文件。

我目前正在使用Angular 5和Mongo DB,但使用它们时我都很新。我试图在survey函数中发布一个名为sendDataToServer的JSON对象。到我的Mongo数据库,但收到的错误表明Cannot read property 'post' of undefined at Array.SignUpComponent.sendDataToServer。我被告知应该使用Observables而不是promises,但我不知道如何实现它,并且愿意接受。

import { Component, OnInit } from '@angular/core';
import { Model, SurveyNG, JsonObject } from 'survey-angular';
import { HttpClient } from '@angular/common/http';
const surveyJSON = { ... } // the JSON object

export class SignUpComponent implements OnInit {

constructor(private http: HttpClient) {}

ngOnInit() {
    const survey = new Model(surveyJSON);
    /*also here, call with this*/
    survey.onComplete.add(this.sendDataToServer);
    SurveyNG.render('surveyElement', { model: survey });
}

    sendDataToServer(survey){
        alert('The results are:' + JSON.stringify(survey.data));
        this.http.post('DATABASE_URL_OMITTED',
        JSON.stringify(survey.data))
        .subscribe(
        (val) => {
          console.log('POST call successful value returned in body',
            val);
        },
        response => {
          console.log('POST call in error', response);
        },
        () => {
          console.log('The POST observable is now completed.');
        });
    }
}

请帮我弄清楚如何将JSON对象发布到数据库。

1 个答案:

答案 0 :(得分:2)

您的sendDataToServer函数是在您注入http服务的Component类之外定义的,这就是为什么在函数内部引用this.http无效的原因。该函数需要在您的类定义中。

@Component({
    selector: 'app-sign-up',
    templateUrl: './sign-up.component.html',
    styleUrls: ['./sign-up.component.css']
})

export class SignUpComponent implements OnInit {

    constructor(private http: HttpClient) {}

    ngOnInit() {
        const survey = new Model(surveyJSON);
        /*also here, call with this*/
        survey.onComplete.add(this.sendDataToServer);
        SurveyNG.render('surveyElement', { model: survey });
    }
    //using arrow method notation makes the `this` keyword behave better
    /*function*/ sendDataToServer=(survey)=>{
        alert('The results are:' + JSON.stringify(survey.data));
        this.http.post('DATABASE_URL_OMITTED',
        JSON.stringify(survey.data))
        .subscribe(
        (val) => {
          console.log('POST call successful value returned in body',
            val);
        },
        response => {
          console.log('POST call in error', response);
        },
        () => {
          console.log('The POST observable is now completed.');
        });
    }

}