简体   繁体   English

从Node.js后端将数据调用到Angular前端

[英]Call data to Angular FrontEnd from Node.js BackEnd

I've got a node.js back-end code calling a database and I need to display this data on my Angular from-end. 我有一个调用数据库的node.js后端代码,我需要在Angular的后端显示这些数据。

This is my back-end code: 这是我的后端代码:

var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

//Own Imports
var cosmosDB = require("./utils/azure-cosmos");
var dataLake = require("./utils/azure-datalake");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};

// render the error page
res.status(err.status || 500);
res.render("error");
});

//Our code starts here
function main() {

//Cosmos Functions
//Gets all devices from cosmos
cosmosDB.findAll("devices", function(docs) {
console.log("Docs found: ", docs);
});

//Gets one device by filter
cosmosDB.findOne("5b4b8d63d08bb1fa920b5f40", "devices", function(docs) 
{
console.log("Doc found find one: ", docs);
});

//Datalake Functions
//Gives you the statuses off all the files in datalake
dataLake.findAll(function(docs) {
console.log("All statuses from datalake: ", docs);
});

//Opens a file with the given name
dataLake.open("5ae6d8e3e892cb63994509fa_1538040038280.json", 
function(doc) {
console.log("Doc requested to be opened: ", doc);
});
}

main();

// app.listen(3000)
console.log("App running on port 3000");

module.exports = app;

I created a api.service.ts on my front-end but I'm clearly missing something! 我在前端创建了一个api.service.ts,但显然缺少某些东西! This is how it looks like at the moment: 现在是这样的:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';


@Injectable()
export class ApiService {

devices = [];

constructor(private http: Http) {}

getDevices() {
this.http.get('http://localhost:3000/devices').subscribe(res => {
  this.devices = res.json();
});
}

How can I correctly implement this so I can use the data on my front-end project? 如何正确实现此目的,以便可以使用前端项目中的数据?

Thank you 谢谢

I think you have to import HttpClient not Http. 我认为您必须导入HttpClient而不是Http。 Try this: 尝试这个:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class ApiService {

devices: any;

constructor(private http:HttpClient) {}

getDevices() {
this.http.get('http://localhost:3000/devices')
    .map(res => res)
    .subscribe(result => this.devices = result);
}

This should work fine try it. 这应该可以正常尝试。

You can also define your own structure of the response and you are sending and use it so that you won't have to use the map function you will get the response directly in that format. 您还可以定义自己的响应结构,然后发送和使用它,这样就不必使用map函数,您将直接以该格式获取响应。 for example: 例如:

export interface Result {
    x: string;
    y: string[];
    ...
}

and use it like 并像这样使用

getDevices(): Observable<Result>{
   this.http.get<Result>('http://localhost:3000/devices')
    .subscribe(result => this.devices = result);

Refer to these stackoverflow questions also which are similar: 请参考以下类似的stackoverflow问题:

Angular - res.json() is not a function Angular-res.json()不是函数

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding Angular2 http.get(),map(),subscribe()和可观察模式-基本理解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM