http: // локальный: 4000 / список выдает ошибку «Невозможно получить / список». Как я могу это исправить? Я думаю, проблема в том, что list.component не взаимодействует с issue.service. Использование angular 6 и http: // localhost: 4000 / вопросы дает правильные данные json из mongodb.
Нужны очень подробные ответы, потому что я пишу код впервые.
list.component.ts:
import { Component, OnInit } from '@angular/core';
import { IssueService } from '../../issue.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
constructor(private issueService: IssueService) { }
ngOnInit() {
this.issueService.getIssues().subscribe((issues) => {
console.info(issues);
});
}
}
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'frontend';
}
issue.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class IssueService {
url = 'http://localhost:4000';
constructor(private http: HttpClient) { }
getIssues() {
return this.http.get(`${this.url}/issues`);
}
getIssueById(id) {
return this.http.get(`${this.url}/issues/${id}`);
}
addIssue(title, responsible, description, severity) {
const issue = {
title: title,
responsible: responsible,
description: description,
severity: severity
};
return this.http.post(`${this.url}/issues/add`, issue);
}
updateIssue(id, title, responsible, description, severity, status) {
const issue = {
title: title,
responsible: responsible,
description: description,
severity: severity,
status: status
};
return this.http.post(`${this.url}/issues/update/${id}`, issue);
}
deleteIssue(id) {
return this.http.get(`${this.url}/issues/delete/${id}`);
}
}
issue.js:
const mongoose = require('mongoose');
const issueSchema = new mongoose.Schema({
title: {
type: String
},
responsible: {
type: String
},
description: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
module.exports = mongoose.model('Issue', issueSchema, 'Issues');
server.js:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Issue = require('./models/issue.js');
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/issues');
const connection = mongoose.connection;
connection.once('open', () => {
console.info('MongoDB database connection established successfully!');
});
app.get("/issues", function(req, res) {
Issue.find({})
.exec(function (err, issues) {
if (err)
console.info(err);
else
res.json(issues);
});
});
app.get("/issues/:id", function(req, res) {
Issue.findById(req.params.id, function(err, issue) {
if (err) {
console.info(err);
} else {
res.json(issue);
}
});
});
app.post("/issues/add", function(req, res) {
var newIssue = new Issue(req.body);
newIssue.save()
.then(item => {
res.send("item saved");
}).catch(err => {
res.status(400).send("failed to save");
});
});
app.put("/issues/update/:id", function(req, res) {
Issue.findById(req.params.id, (err, issue) => {
if (!issue)
return next(new Error("could not find ID"));
else {
issue.title = req.body.title;
issue.responsible = req.body.responsible;
issue.description = req.body.description;
issue.severity = req.body.severity;
issue.status = req.body.status;
issue.save()
.then(item => {
res.send("item updated");
}).catch(err => {
res.status(400).send("failed to update");
});
};
});
});
app.delete("/issues/delete/:id", function(req, res) {
Issue.findByIdAndRemove({_id: req.params.id}, (err, issue) => {
if (err)
res.json(err);
else
res.json('Removed successfully');
})
});
app.use('/', router);
app.listen(4000, () => console.info('Express server running on port 4000'));
Стоит ли добавлять маршрут в файл server.js?
файл маршрутов обычно называется app.routes.ts или что-то подобное - его содержимое должно выглядеть примерно так ... {путь: 'issues', component: IssuesComponent,
Похоже, у вас нет маршрута с названием / list