无法通过angular从nodejs获取数据

时间:2018-06-10 21:57:03

标签: mysql node.js angular

我无法通过角度6从nodejs获取数据。 我添加了一个服务来连接它们但它没有工作

我成功通过nodejs服务器获取数据..但我无法在角度组件上接收它。

我知道我错过了他们之间的联系,但我无法解决它。

HostingstartComponent.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);
      });
    }
}

aService.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);

app.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!'))

1 个答案:

答案 0 :(得分:0)

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

您:

this.aService.getData()

应该是:

this.service.getData()

另外在ngOnInit中调用myFunc()

ngOnInit() {
  this.myFunc()
}