首页 > 解决方案 > 从 Node.js 后端调用数据到 Angular 前端

问题描述

我有一个调用数据库的 node.js 后端代码,我需要在我的 Angular 从端显示这些数据。

这是我的后端代码:

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;

我在前端创建了一个 api.service.ts ,但我显然遗漏了一些东西!这是它目前的样子:

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();
});
}

如何正确实现这一点,以便可以在前端项目中使用数据?

谢谢

标签: node.jsangularangular2-services

解决方案


我认为你必须导入 HttpClient 而不是 Http。尝试这个:

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

这应该可以正常尝试。

您还可以定义自己的响应结构并发送和使用它,这样您就不必使用 map 函数,您将直接以该格式获得响应。例如:

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

并像使用它一样

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

请参阅这些类似的 stackoverflow 问题:

Angular - res.json() 不是函数

Angular2 http.get() ,map(), subscribe() 和 observable 模式 - 基本理解


推荐阅读