您好我有服务将数据发送到我的服务器:
import { Injectable} from '@angular/core';
import { Http, Response,Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Transaction } from './transaction'
@Injectable()
export class TransactionSenderService{
constructor(private http:Http){}
private url = 'http://localhost:3000/transaction/save/';
sendTransaction(ta: Transaction) : Observable<Boolean>{
let bodyString = JSON.stringify(ta);
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this.url,bodyString,options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = <Boolean>res.json();
return body || {};
}
private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
并在我的express.js
部分:
app.post('/transaction/save/', (req, res)=>{
var ta = req.body.ta;
res.send("done");
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
问题是我的请求没有被发送?
我无法在浏览器的网络选项卡中看到任何内容。我在express.js中也有断点,所以我看到没有收到任何东西。如果我是从Postman
发送的,那么它正在运行。控制台中没有异常/错误。我做错了什么?
@UPDATE
我被要求放在这里,我打电话给这个发送:
export class MainComponent implements OnChanges, OnInit, OnDestroy {
isModalVisible: Boolean;
transactions: Transaction[];
selectedTa: number;
constructor(private transactionSenderService: TransactionSenderService) {}
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
alert("Wykrywam Zmiany");
}
ngOnDestroy(){
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
myValueChange(event: any) {
console.log(event);
}
clearTa(): void {
this.transactionSenderService.sendTransaction(this.transactions[this.selectedTa])
}
}
我删除了不必要的代码。这个片段正在运行。我可以一步一步地看到我要进入send方法。
如果我将observable
更改为toPromise
而不是发送请求,请执行更多操作。为什么呢?
答案 0 :(得分:2)
您需要订阅observable来发出请求,更改您拨打电话的地方。
this.transactionSenderService.sendTransaction(this.transactions[this.selectedTa]).subscribe(resp => {
});