组件和服务之间的Angular 6通信

时间:2018-09-27 00:48:31

标签: angular

http://localhost:4000/list给出“无法获取/列表”错误。我怎样才能解决这个问题?我认为问题是list.component无法与issue.service通信。使用角度6,http://localhost:4000/issues从mongodb提供正确的json数据。

需要非常详细的答案,因为我是第一次进行编码。

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.log(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.log('MongoDB database connection established successfully!');
});

app.get("/issues", function(req, res) {
    Issue.find({})
    .exec(function (err, issues) {
        if (err)
            console.log(err);
        else
            res.json(issues);
    });
});

app.get("/issues/:id", function(req, res) {
    Issue.findById(req.params.id, function(err, issue) {
        if (err) {
            console.log(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.log('Express server running on port 4000'));

0 个答案:

没有答案