将猫鼬数据传递到一个角度4的组件'细节'页?

时间:2017-05-25 04:22:19

标签: javascript angular mongoose

我对角4和猫鼬来说很新,我甚至不肯定我正确地做到了这一点。我有一个页面,列出了学校。我可以将学校添加到数据库中,当我点击其中一个名称(school.name)时,我会将其转到详细信息页面。我在{ path: 'api/schools/:id', component: SchoolDetailComponent }标记的html模板中设置了类似routerLink="/api/schools/{{school._id}}"的路由,该标记成功加载了具有正确ID号的网址http://localhost:3000/api/schools/592641e61e4e76cfda292b4a(显然特定于任何元素。)我不确定如何将特定元素的信息加载到详细信息页面。

学校架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;

var schoolsSchema = new Schema({
  // _id
  name: { type: String, required: true },
  wave: { type: Number, default: 0 }, // of questions sent out
  questionCount: { type: Number, default: 0 },
  date: { type: Date, default: Date.now }, // created
  phaseGate: {type: Number, default: 0},
  disabled: {type: Boolean, default: false}
});

// Export the Mongoose model
module.exports = mongoose.model('School', schoolsSchema);

API:

    var router = require('express').Router();
    var School = require('../models/schools');
    var User = require('../models/users');
    var lock = require('./api-lock');

    // server routes thru /api/schools/ path
    // api/schools/ when calling from client

// SCHOOLS/ ROUTE >>>>>>>>>>>>
router.route('/')
    // GET REQUEST
    .get(lock.requireAdmin, (req, res) => {

        School
        .find({'disabled': { $in: [false, null]}}) // find all Schools
        .sort('-date')
        .exec((err, schools) => {
            if(err) {
                res.json(500, {msg: "error"});
            }
            res.json(schools);
        });
    })
    // POST REQUEST
    .post(lock.requireAdmin, (req, res) => {
        // create new school profile
        School.create(req.body, (err, school) => {
            if(err) {
              return res.json({msg: "error"});
            }
            res.json(school);
          });
    });


// SCHOOLS/WAVE/ ROUTE >>>>>>>>>>>>
router.route('/wave/update/')
    // PUT REQUEST
    // update wave count on school
    .put(lock.requireAdmin, (req, res) => {

        var schoolId = req.body._id;

        School
        .findOneAndUpdate(
            { _id: schoolId }, // find indv School
            { $inc: { wave: 1}}, // replace name
            {new: true},
            (err, school) => {
                res.json(school);
            }
        )
    });


// SCHOOLS/:SCHOOL_ID ROUTE >>>>>>>>>>>>
router.route('/:id')
    // GET REQUEST
    .get(lock.requireSchoolAdmin, (req, res) => {
        School
        .findById({
            _id: req.params.school_id, // find indv School
      //disabled: { $in: [false, null]}
        })
        .select()
        .exec((err, school) => {
            if(err){
                res.status(500).send('School not found.')
            }
            res.json(school);
        });
    })
    // PUT REQUEST
    .put(lock.requireAdmin, (req, res) => {

        console.log(req);
        School
        .findOneAndUpdate(
            { _id: req.params.school_id }, // find indv School
            { $set: { name: req.body.name }}, // replace name
            (err, school) => {
                res.json(school);
            }
        )
    })

// SCHOOLS/:SCHOOL_ID ROUTE >>>>>>>>>>>>
router.route('/phase/update/')
    // PUT REQUEST
    // Update school phaseGate
    .put(lock.requireAdmin, (req, res) => {

        console.log(req);
        School
        .findOneAndUpdate(
            { _id: req.params.school_id }, // find indv School
            { $inc: {"phaseGate": 1 }}, // replace name
            (err, school) => {
                res.json(school);
            }
        )
    })


// SCHOOLS/COUNT/TOTAL/ ROUTE >>>>>>>>>>>>
router.route('/count/total/')
    // GET REQUEST
    .get(lock.requireAdmin, (req, res) => {
        School
        .count({}) // find School count total
        .exec((err, count) => {
            res.json(count);
        });
    });


module.exports = router;

学校明细组成部分:

import { Component, OnInit } from '@angular/core';

import { Http } from '@angular/http';
import { FormGroup, FormControl, Validators, FormBuilder } from     '@angular/forms';
import {  ActivatedRoute, Params } from '@angular/router';

import { SchoolService } from '../services/school.service';

@Component({
  selector: 'app-school-detail',
  templateUrl: './school-detail.component.html',
  styleUrls: ['./school-detail.component.css']
})
export class SchoolDetailComponent implements OnInit {

  schools = [];
  school = {};

  admins = [];
  admin = {};

  constructor(private http: Http,
    private schoolService: SchoolService,
    private userService: UserService,
              private formBuilder: FormBuilder,
            private activatedRoute: ActivatedRoute) {

          // route.snapshot.params['id'];
          // console.log('id');
         }
  ngOnInit() {
    this.getSchools();
    // this.getSchool();
    //
    console.log(this.school);
    });

    // this.activatedRoute.params.subscribe((params: Params) => {
    //     let schoolId = params['schoolId'];
    //     console.log(schoolId);
//   });

      // let SchoolId = this.route.snapshot.params["SchoolId"];
      // console.log(SchoolId);
  }

  //schools
  getSchools() {
    this.schoolService.getSchools().subscribe(
      data => this.schools = data,
      error => console.log(error),
      // () => this.isLoading = false
    );
  }

  // getSchool() {
  //   this.schoolService.getSchool().subscribe(
  //     data => this.school = data,
  //     error => console.log("getSchool" + error),
  //     // () => this.isLoading = false
  //
  //   );
  //   console.log(this.school)
  // }

  // getSchool(school) {
  //
  //     this.schoolService.getSchools(school).subscribe(
  //       res => {
  //         const pos = this.schools(school._id);
  //         // console.log(this.schools.map(elem => { return elem._id;     }).indexOf(school._id));
  //         console.log(school._id);
  //         // this.schools.splice(pos, 1);
  //
  //         // console.log(this.schools);
  //         // this.toast.setMessage('item deleted successfully.',     'success');
  //       },
  //       error => console.log(error)
  //     );
  // }
}

在html中,我试图在html中调用school.name。我在上面的组件代码中评论过,我尝试过使用ActivatedRoute,但它似乎并不想工作。我试过浏览谷歌,堆栈溢出,github,youtube,似乎无法让它发挥作用。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用activatedRoute.snapshot.params [' id'];

public schoolname: string;

 constructor(private http: Http,private schoolService: SchoolService,private userService: UserService,private formBuilder: FormBuilder,
                private activatedRoute: ActivatedRoute) {
                this.schoolname=activatedRoute.snapshot.params['id'];       
             }

ngOnInit() {

console.log(this.schoolname)

 }