【发布时间】:2018-04-06 19:34:02
【问题描述】:
我找不到解决问题的方法,但请随时为我提供一些可以提供帮助的链接。这是完整的sign-up.component.ts 文件。
我目前正在使用 Angular 5 和 Mongo DB,但对使用它们都非常陌生。我试图在sendDataToServer 函数中发布一个名为survey 的JSON 对象。到我的 Mongo DB,但收到一条错误消息,指出 Cannot read property 'post' of undefined
at Array.SignUpComponent.sendDataToServer。有人告诉我应该使用 Observables 而不是 Promise,但我不知道如何实现它并且对想法持开放态度。
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 对象发布到数据库。
【问题讨论】:
-
您的方法 sendDataToServer 是否应该在您的 SignUpComponent 中?您也没有将任何参数传递给 sendDataToServer 方法:survey.onComplete.add(sendDataToServer);
-
survey.data 无法工作,因为调查未定义
-
我在网上找到了这个解决方案,
survey.onComplete中的survey出于某种原因成为sendDataToServer的参数,并在sendDataToServer中创建了一个带有已定义survey的填充警报框.