這是我的代碼;發送請求重新啓動服務器而不發送數據(Angular2/Node.js)
服務:
import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/Rx';
import {Heatmap} from "./heatmap"
@Injectable()
export class HeatmapService {
constructor (private _http: Http) {}
signup(heatmap: Heatmap) {
const body = JSON.stringify(heatmap);
const headers = new Headers({'Content-Type': 'application/json'});
const options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:8080/create', body, options)
.map(response => response.json())
.catch(error => Observable.throw(error.json()));
}
}
組件:
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, FormControl, Validators } from "@angular/forms";
import { Heatmap } from "./heatmap";
import { HeatmapService } from "./heatmap.service";
@Component({
templateUrl: 'js/app/heatmap/heatmap.component.html'
})
export class heatmapComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder, public heatService: HeatmapService) {}
onSubmit() {
const heatmap = new Heatmap(this.myForm.value.name, this.myForm.value.data, this.myForm.value.country);
console.log(heatmap)
this.heatService.sendData(heatmap)
.subscribe(
data => console.log(data),
error => console.error(error)
)
}
ngOnInit() {
this.myForm = this.formBuilder.group({
name: ['', Validators.required],
data: ['', Validators.required],
country: ['', Validators.required]
});
}
}
HTML:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">name</label>
<input type="text" id="name" class="form-control" formControlName="name">
</div>
<div class="form-group">
<label for="data">data</label>
<input type="text" id="data" class="form-control" formControlName="data">
</div>
<div class="form-group">
<label for="country">country</label>
<input type="text" id="country" class="form-control" formControlName="country">
</div>
<button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Sign Up</button>
</form>
熱圖:
export class Heatmap {
constructor(public name: string, public data: string, public country: string){}
}
問題:
每次我提交我的表單時,我的服務器會自動重啓,沒有數據記錄,並且沒有時間查看任何正在安慰的錯誤。
我得到的唯一錯誤來自一飲而盡輸出 -
錯誤TS2339:房產「送出數據」不上鍵入「HeatmapService」存在。
希望有人能幫助!
對不起,我正在嘗試像'this.heatService(heatmap)'這樣做,在此之前,我在一些教程中看到了一些工作。我只是建立了聯繫。 – since095