我正在尝试将数据从角度发布到节点API,但数据没有发布
我已经设置了一个节点API,在angular上设计了一个简单的文本框和按钮,单击时,应将文本框值发布到node API,数据没有发布,也没有来自angular的subscribe方法的响应
ins.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import {Observable,Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InsService {
name: String;
constructor(private http:Http) { }
postAPIData(name: String):Observable<any>{
console.log("hi");
return this.http.post('http://localhost:3000/', {"name":name})
}
}
ins.component.ts
import { Component, OnInit } from '@angular/core';
import {InsService} from '../ins.service'
@Component({
selector: 'app-ins',
templateUrl: './ins.component.html',
styleUrls: ['./ins.component.css']
})
export class InsComponent {
ivalue:String;
ins:InsService;
constructor()
{
}
insoperation(insertion:String)
{
if(insertion)
{
this.ivalue=insertion;
console.log(this.ivalue);
this.postdata();
}
}
postdata()
{
()=>{this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
})};
}
}
server.js
var express=require("express");
var app=express();
var bodyParser = require('body-parser')
var cors = require("cors");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000,"localhost",function(req,res,next){
console.log("Server running on port 3000");
})
app.all("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.post('/',function(req,res,next){
console.log(req.body);
})
我希望数据将从角度发布到节点
答案 0 :(得分:-1)
在构造函数中定义服务
constructor(private ins:InsService ) {}
并从
中删除引用 ins:InsService; // this line
您需要将angular的postdata方法更改为
(()=>{this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
})})();
或
postdata()
{
this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
});
}
您正在定义未执行的箭头功能
答案 1 :(得分:-1)
第inst: InService
行仅告诉TypeScript变量的类型。您需要在构造函数中定义服务才能使用。
比起postdata()
函数中的箭头函数,您可以摆脱它:
inst: InService // Remove this line, instead define it in your constructor
constructor(private ins:InsService ) {}
postdata(){
this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
})};
}