首页 > 解决方案 > 无法将数据从角度发布到节点 api

问题描述

我正在尝试将数据从角度发布到节点 API,数据没有被发布

我已经设置了一个节点 API,在 angular 上设计了一个简单的文本框和按钮,单击时,文本框值应该发布到节点 API,数据没有被发布,也没有来自 angular 订阅方法的响应

安装服务.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);
        })};
    }

    }

服务器.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);
    })

我希望数据从角度发布到节点

标签: node.jsangular

解决方案


在构造函数中定义服务

constructor(private ins:InsService  ) {}

并从中删除参考

  ins:InsService; // this line

您需要将角度上的 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);
    });
}

您正在定义一个未执行的箭头函数


推荐阅读