无法从nodejs获取数据

m528fe3b  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(320)

嗨,我在6点之前无法从nodejs获取数据。我添加了一个服务来连接它们,但它不起作用。
我成功地通过nodejs服务器获取了数据,但是在Angular 组件上接收不到数据。
我知道我错过了他们之间的联系,但我不能解决它。
主机启动组件.ts

import { Component, OnInit } from '@angular/core';
import { NgAnalyzedFile } from '@angular/compiler';
import {RouterModule ,Routes } from '@angular/router'; 
import {HttpModule, Http} from '@angular/http'
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SecComponent } from '../sec/sec.component';
import { ThirdComponent } from '../third/third.component';
import {aService} from '../services/a.service';
@Component({
  selector: 'app-hostingstart',
  templateUrl: './hostingstart.component.html',
  styleUrls: ['./hostingstart.component.css']
})
export class HostingstartComponent implements OnInit {
  aService: any;
  data: any;
   appRoutes : Routes=[
    {path: 'hostingstar',component : HostingstartComponent},
    {path: '',component : HostingstartComponent},
    {path: 'sec',component : SecComponent, data : {some_data : 'some value'}},
    {path: 'third',component : ThirdComponent, data : {some_data : 'some value'}}
  ]; 

  headImg : any="assets/images/pan.JPG";
  constructor(private http: Http , private service: aService) { 
    this.headImg ="assets/images/pan.JPG";
  //  this.aService.getData().then( (result) => {this.data = result; });
  }

  ngOnInit() {
   // alert(this.aService.getData());
   // this.aService.getData().then( (result) => {this.data = result; });
   // alert(this.data);
   }

   myFunc() {
    //this.router.navigate(['/third', 'north']);
   // alert( document.getElementById("search-input").value);

    }
    getData() {

      this.aService.getData().subscribe((dataFromServer) => {

        this.data=dataFromServer;
        // Now you can use the data
       // alert(dataFromServer)
        console.log(dataFromServer);
      });
    }
}

A服务.ts

import 'rxjs/add/operator/toPromise';
import { Http, Response, Headers } from '@angular/http';
import { Injectable } from '@angular/core';

@Injectable()
export class aService {

  constructor(private http: Http) {
  }

 async getData() {
    const options = {
      headers: new Headers({
        'Content-Type':  'application/json;charset=utf-8',
        'Access-Control-Allow-Origin': '*'
      })
    };

    // const url = './assets/heroes.data.json';
    const url = 'http://localhost:3000/';
    return this.http.get(url, options)
      .toPromise()
      .then(response => {
        if (response != null) {
          const result = response.json();
          return Promise.resolve(result);
        }
        return [];
      })
      .catch(err => {
        console.warn('error in getCats', err);
        return Promise.reject(null);
      });
  }    
}

节点js:index.js

console.log('Running File: index.js')
    //-- Create Express Server:

    var express = require('express');
    var app = express();
    var util = require('util');

    var mysql = require('mysql');
    var a;
    var con = mysql.createConnection({
        host : 'localhost',
        user: 'node',
        password : 'arafat1990!@#$',
        database: "iTour"
    });
    con.connect(function(err) {
        if (err) throw err;
        con.query("SELECT * FROM feedback", function (err, result, fields) {
          if (err) throw err;
        //  console.log(result);
          a=result;
        });
      });
    //-- Map Base URL to res (Response)
    app.get('/', function(req, res){
            var fname = req.query.fname;
            var lname = req.query.lname;

            var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
            res.send(a);
        });
        app.get('/hostingstar', function(req, res){
          var fname = req.query.fname;
          var lname = req.query.lname;

          var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
          res.send(a);
      });

    //-- Listen on Port 3000:
    app.listen(3000);

应用程序.js

const express = require('express');
const app = express();
//const firebase = require('firebase-admin');

app.get('/hostingstart', (req, res) => res.send('Server Is Active!'))
app.get('/hostingstart', (req, res) => {

  var mysql = require('mysql');
  var connection = mysql.createConnection({
    host : 'localhost',
    user: 'node',
    password : 'arafat1990!@#$',
    database: "iTour"
  });

  connection.connect();
  connection.query('SELECT * FROM feedback;', function (error, results, fields) {
    if (error) {
      console.warn(error);
      res.send('');
      return;
    }
    console.log("Result: " + results);
    res.send(results);
  });

  connection.end();
})

app.get('/hostingstart', (req, res) => {

  var ref = firebase.app().database().ref();
  ref.once("value").then(function (snap) {
    console.log("snap.val()", snap.val());
    res.send(snap.val());
  });    
});

app.use(function(req, res, next){
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

  // Check if preflight request
    if (req.method === 'OPTIONS') {
        res.status(200);
        res.end();
    }
    else {
        next();
    }
});

app.listen(3000, () => console.log('Server is listening on port 3000!'))
jv2fixgn

jv2fixgn1#

在getservice方法中,您调用的是服务本身,而不是构造函数的属性。
您的:

this.aService.getData()

应该是:

this.service.getData()

在ngoninit中另外调用myfunc()

ngOnInit() {
  this.myFunc()
}

相关问题