我有一个调用数据库的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();
});
}
如何正确实现此目的,以便可以使用前端项目中的数据?
谢谢
我认为您必须导入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问题: