Как отобразить несколько схем моделей в ngOnInit () Angular, Mongodb, Express - PullRequest
0 голосов
/ 21 марта 2019

В настоящее время я пытаюсь загрузить две отдельные схемы моделей на мой home-page.html, используя 'let cat of cats' и 'let dog of dogs'.Когда моя домашняя страница загружается, я хочу, чтобы она заполняла каждую таблицу данными соответствующего животного, но вместо этого она будет загружать кошек на обоих столах или собак, только если я переключу this.dogs = data на this.cats = data

Это мои модели.

var mongoose = require('mongoose');

var CatSchema = new mongoose.Schema({
    breedname: { type: String, required: true, minlength: 3 },
    age: { type: Number, required: true, minlength: 2 },
    gender: { type: String, required: true},
    comfortablecatdog: { type: String},
    comfortablekids: { type: String},
    health: { type: String, required: true},

}, { timestamps: true });

mongoose.model('Cat', CatSchema);

var DogSchema = new mongoose.Schema({
    breedname: { type: String, required: true, minlength: 3 },
    age: { type: Number, required: true, minlength: 2 },
    gender: { type: String, required: true},
    comfortablecatdog: { type: String},
    comfortablekids: { type: String},
    health: { type: String, required: true},

}, { timestamps: true });

mongoose.model('Dog', DogSchema);

Мои контроллеры ..

var mongoose = require("mongoose");
var Cat = mongoose.model('Cat');
var Dog = mongoose.model('Dog');
module.exports = {
    index: function (req, res) {
        console.log('hit index controller');
        Cat.find({}, function (err, breedname) {
            if (err) {
                console.log('got an error at index');
                res.json(err);
            } else {
                console.log('rendered cats');
                res.json(breedname);
            }
        })
        Dog.find({}, function (err, breedname) {
            if (err) {
                console.log('got an error at index');
                res.json(err);
            } else {
                console.log('rendered dogs');
                res.json(breedname);
            }
        })

    },

Моя домашняя страница html ..

<div class="row" style="margin: 1px; padding: 15px;">
  <div class="table-responsive table-sm shadow-lg w-auto"
    style="border: 1px solid black; cursor: default; padding-right: 0; border-radius: 8px;">
    <table class="table table-hover w-auto" style="margin: 0; border-radius: 18px;">
      <thead>Cats
        <tr
          style="/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#fac695+0,f5ab66+47,ef8d31+100;Orange+3D+%232 */
        background: rgb(250,198,149); /* Old browsers */
        background: -moz-linear-gradient(top, rgba(250,198,149,1) 0%, rgba(245,171,102,1) 47%, rgba(239,141,49,1) 100%); /* FF3.6-15 */
        background: -webkit-linear-gradient(top, rgba(250,198,149,1) 0%,rgba(245,171,102,1) 47%,rgba(239,141,49,1) 100%); /* Chrome10-25,Safari5.1-6 */
        background: linear-gradient(to bottom, rgba(250,198,149,1) 0%,rgba(245,171,102,1) 47%,rgba(239,141,49,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
        filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fac695', endColorstr='#ef8d31',GradientType=0 ); /* IE6-9 */; font-size: 25px; color: whitesmoke; font-size: 17px;">
          <th scope="col">Breed Name</th>
          <th scope="col">Age</th>
          <th scope="col">Gender</th>
          <th scope="col">Comfortable around other pets/animals?</th>
          <th scope="col">Comfortable around children/people?</th>
          <th scope="col">Any known health issues?</th>
          <th scope="col">Actions</th>
        </tr>
      </thead>
      <tbody style="font-size: 17.1px;">
        <tr *ngFor="let cat of cats">
          <td>{{cat.breedname}}</td>
          <td>{{cat.age}}</td>
          <td>{{cat.gender}}</td>
          <td>{{cat.comfortablecatdog}}</td>
          <td>{{cat.comfortablekids}}</td>
          <td>{{cat.health}}</td>
          <button
            style="border: 1.5px solid rgba(0, 164, 240, 0.267); background-color: whitesmoke; border-radius: 23px; font-size: 15px; padding: 5px; margin: 5px;"
            [routerLink]="['/cats', cat._id]">Details</button>
          <button
            style="border: 1.5px solid rgba(255, 217, 0, 0.267); background-color: whitesmoke; border-radius: 23px; font-size: 15px; padding: 5px; margin: 5px;"
            [routerLink]="['/cats', cat._id, 'edit']">Edit</button>
          <!-- <button style="border: 1.5px solid rgba(255, 0, 0, 0.226); background-color: whitesmoke; border-radius: 23px; font-size: 15px; padding: 5px; margin: 5px;"
            [routerLink]="['/cats', cat._id, 'delete']">Delete</button> -->
        </tr>
      </tbody>
    </table>
  </div>
</div>
<div class="row" style="margin: 1px; padding: 15px;">
  <div class="table-responsive table-sm shadow-lg w-auto"
    style="border: 1px solid black; cursor: default; padding-right: 0; border-radius: 8px;">
    <table class="table table-hover w-auto" style="margin: 0; border-radius: 18px;">
      <thead>Dogs
        <tr
          style="/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#fac695+0,f5ab66+47,ef8d31+100;Orange+3D+%232 */
        background: rgb(250,198,149); /* Old browsers */
        background: -moz-linear-gradient(top, rgba(250,198,149,1) 0%, rgba(245,171,102,1) 47%, rgba(239,141,49,1) 100%); /* FF3.6-15 */
        background: -webkit-linear-gradient(top, rgba(250,198,149,1) 0%,rgba(245,171,102,1) 47%,rgba(239,141,49,1) 100%); /* Chrome10-25,Safari5.1-6 */
        background: linear-gradient(to bottom, rgba(250,198,149,1) 0%,rgba(245,171,102,1) 47%,rgba(239,141,49,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
        filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fac695', endColorstr='#ef8d31',GradientType=0 ); /* IE6-9 */; font-size: 25px; color: whitesmoke; font-size: 17px;">
          <th scope="col">Breed Name</th>
          <th scope="col">Age</th>
          <th scope="col">Gender</th>
          <th scope="col">Comfortable around other pets/animals?</th>
          <th scope="col">Comfortable around children/people?</th>
          <th scope="col">Any known health issues?</th>
          <th scope="col">Actions</th>
        </tr>
      </thead>
      <tbody style="font-size: 17.1px;">
        <tr *ngFor="let dog of dogs">
          <td>{{dog.breedname}}</td>
          <td>{{dog.age}}</td>
          <td>{{dog.gender}}</td>
          <td>{{dog.comfortablecatdog}}</td>
          <td>{{dog.comfortablekids}}</td>
          <td>{{dog.health}}</td>
          <button
            style="border: 1.5px solid rgba(0, 164, 240, 0.267); background-color: whitesmoke; border-radius: 23px; font-size: 15px; padding: 5px; margin: 5px;"
            [routerLink]="['/dogs', dog._id]">Details</button>
          <button
            style="border: 1.5px solid rgba(255, 217, 0, 0.267); background-color: whitesmoke; border-radius: 23px; font-size: 15px; padding: 5px; margin: 5px;"
            [routerLink]="['/dogs', dog._id, 'edit']">Edit</button>
          <!-- <button style="border: 1.5px solid rgba(255, 0, 0, 0.226); background-color: whitesmoke; border-radius: 23px; font-size: 15px; padding: 5px; margin: 5px;"
            [routerLink]="['/dogs', dog._id, 'delete']">Delete</button> -->
        </tr>
      </tbody>
    </table>
  </div>
</div>

И моя домашняя страница.ts

export class HomePageComponent implements OnInit {
  newCat: any;
  newDog: any;
  cats = [];
  dogs = [];
  // cat = {breedname: ''};
  // dog = {breedname: ''};


  constructor(private _route: ActivatedRoute, private _httpService: HttpService, private _router: Router, ) { }

  ngOnInit() {
    var tempObeservable = this._httpService.getAllPets();
    tempObeservable.subscribe((data: any) => {
      console.log('got a response from ngoninit', data);
      this.dogs = data;
      this.cats = data;
    });
  }

Мои http.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { identifierModuleUrl } from '@angular/compiler';

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(private _http:HttpClient) { }
  getAllPets(){
    console.log('getAllPets');
    return this._http.get('/api/pets');
  }
  getCatById(_id){
    console.log('getCatById');
    let breedquestion = this._http.get(`/api/pets/${_id}/editcat`);
    return breedquestion;
  }
  getDogById(_id){
    console.log('getDogById');
    let breedquestion = this._http.get(`/api/pets/${_id}/editdog`);
    return breedquestion;
  }
  updateCatInfo(breedObj){
    console.log('UpdateCat')
    return this._http.post('/api/pets/'+breedObj._id+'/updatecat', breedObj);
  }
  updateDogInfo(breedObj){
    console.log('UpdateDog')
    return this._http.post('/api/pets/'+breedObj._id+'/updatedog', breedObj);
  }
  postNewCat(breedObj){
    console.log('postnewCat')
    return this._http.post('/api/pets/newcat', breedObj);
  }
  postNewDog(breedObj){
    console.log('postnewDog')
    return this._http.post('/api/pets/newdog', breedObj);
  }

мои контроллеры с закомментированным кодом

var mongoose = require("mongoose");
var Cat = mongoose.model('Cat');
var Dog = mongoose.model('Dog');
module.exports = {
    index: function (req, res) {
        console.log('hit index controller');
        // When the page loads, I want my Cats and Dogs to load into each of their tables

        Cat.find({}, function (err, breedname) {
            if (err) {
                console.log('got an error at index');
                res.json(err);
            } else {
                console.log('rendered cats');
                res.json(breedname);
            }
        })
        Dog.find({}, function (err, breedname) {
            if (err) {
                console.log('got an error at index');
                res.json(err);
            } else {
                console.log('rendered dogs');
                res.json(breedname);
            }
        // -----------------------------------------

        })
    },

Я уже знаю, что мой ngOnInit ()взяв два параметра 'data', когда он должен быть только один, я просто оставил это так, потому что я не уверен, что делать.Здесь немного новичка.

Есть предложения?Извиняюсь, если на это уже был дан ответ.

Спасибо.

1 Ответ

0 голосов
/ 22 марта 2019

сначала исправьте свой контроллер, чтобы дать как кошкам, так и собакам что-то вроде этого

Promise.all([
  Cat.find({}).exec(),
  Dog.find({}).exec()
])
.then(([cats, dogs]) => res.json({cats, dogs}))
.catch((err) => res.status(500).json(err))

, а затем исправьте подписку для обработки этого

 tempObeservable.subscribe(({cats, dogs}) => {
      console.log('got a response from ngoninit', cats, dogs);
      this.dogs = dogs;
      this.cats = cats;
    });

проблема в том, что вы пытаетесьответить 2 раза на один запрос в вашем бэкэнд-коде, и это невозможно.Я ответил 1 раз с помощью объекта {cats, dogs} json

...