Angular 2,MEAN Stack:接收JSON而不是HTML

时间:2016-12-13 12:34:41

标签: json angular mean

我正在添加一条名为“dog”的Angular 2 Full Stack repo路由,命令行中没有错误,表中的数据很好用

有2个组件

cat:HomeComponent,path''

dog:DogComponent,path'/ dog'

enter image description here

但是当我刷新页面时,我得到了原始的JSON而不是HTML

enter image description here

app.js 

var express = require('express');
var path = require('path');
var morgan = require('morgan'); // logger
var bodyParser = require('body-parser');

var app = express();
app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(__dirname + '/../../dist'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(morgan('dev'));

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;
mongoose.Promise = global.Promise;

// Models
var Cat = require('./cat.model.js');
var Dog = require('./dog.model.js');

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB');

  // APIs
  // select all
  app.get('/cats', function(req, res) {
    Cat.find({}, function(err, docs) {
      if(err) return console.error(err);
      res.json(docs);
    });
  });

  // count all
  app.get('/cats/count', function(req, res) {
    Cat.count(function(err, count) {
      if(err) return console.error(err);
      res.json(count);
    });
  });

  // create
  app.post('/cat', function(req, res) {
    var obj = new Cat(req.body);
    obj.save(function(err, obj) {
      if(err) return console.error(err);
      res.status(200).json(obj);
    });
  });


  // find by id
  app.get('/cat/:id', function(req, res) {
    Cat.findOne({_id: req.params.id}, function(err, obj) {
      if(err) return console.error(err);
      res.json(obj);
    })
  });

  // update by id
  app.put('/cat/:id', function(req, res) {
    Cat.findOneAndUpdate({_id: req.params.id}, req.body, function(err) {
      if(err) return console.error(err);
      res.sendStatus(200);
    })
  });

  // delete by id
  app.delete('/cat/:id', function(req, res) {
    Cat.findOneAndRemove({_id: req.params.id}, function(err) {
      if(err) return console.error(err);
      res.sendStatus(200);
    });
  });

  app.get('/dog', function(req, res) {
    Dog.find({}, function(err, docs) {
      if(err) return console.error(err);
      res.json(docs);
    });
  });

  // create
  app.post('/dog', function(req, res) {
    var obj = new Dog(req.body);
    obj.save(function(err, obj) {
      if(err) return console.error(err);
      res.status(200).json(obj);
    });
  });



  // all other routes are handled by Angular
  app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname,'/../../dist/index.html'));
  });

  app.listen(app.get('port'), function() {
    console.log('Angular 2 Full Stack listening on port '+app.get('port'));
  });
});

module.exports = app;

这是app.module路线

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { DataService } from './services/data.service';

import { ToastComponent } from './shared/toast/toast.component';
import {DogComponent} from "./dog/dog.component";

const routing = RouterModule.forRoot([
  { path: '',      component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'dog', component: DogComponent }

]);

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent,
    ToastComponent,
    DogComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    routing
  ],
  providers: [
    DataService,
    ToastComponent
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  bootstrap: [AppComponent]
})

export class AppModule { }

data.service

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class DataService {

  private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
  private options = new RequestOptions({ headers: this.headers });

  constructor(private http: Http) { }

  getCats(): Observable<any> {
    return this.http.get('/cats').map(res => res.json());
  }

  addCat(cat): Observable<any> {
    return this.http.post("/cat", JSON.stringify(cat), this.options);
  }

  editCat(cat): Observable<any> {
    return this.http.put(`/cat/${cat._id}`, JSON.stringify(cat), this.options);
  }

  deleteCat(cat): Observable<any> {
    return this.http.delete(`/cat/${cat._id}`, this.options);
  }

  getDogs(): Observable<any> {
    return this.http.get('/dog').map(res => res.json());
  }

  addDog(dog): Observable<any> {
    return this.http.post("/dog", JSON.stringify(dog), this.options);
  }

  editDog(dog): Observable<any> {
    return this.http.put(`/dog/${dog._id}`, JSON.stringify(dog), this.options);
  }

  deleteDog(dog): Observable<any> {
    return this.http.delete(`/dog/${dog._id}`, this.options);
  }

}

我包含了dog.component.ts,但它认为你可以忽略它

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class DataService {

  private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
  private options = new RequestOptions({ headers: this.headers });

  constructor(private http: Http) { }

  getCats(): Observable<any> {
    return this.http.get('/cats').map(res => res.json());
  }

  addCat(cat): Observable<any> {
    return this.http.post("/cat", JSON.stringify(cat), this.options);
  }

  editCat(cat): Observable<any> {
    return this.http.put(`/cat/${cat._id}`, JSON.stringify(cat), this.options);
  }

  deleteCat(cat): Observable<any> {
    return this.http.delete(`/cat/${cat._id}`, this.options);
  }

  getDogs(): Observable<any> {
    return this.http.get('/dog').map(res => res.json());
  }

  addDog(dog): Observable<any> {
    return this.http.post("/dog", JSON.stringify(dog), this.options);
  }

  editDog(dog): Observable<any> {
    return this.http.put(`/dog/${dog._id}`, JSON.stringify(dog), this.options);
  }

  deleteDog(dog): Observable<any> {
    return this.http.delete(`/dog/${dog._id}`, this.options);
  }

}

我改变了

const routing = RouterModule.forRoot([
  { path: '',      component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'dog', component: DogComponent }

]);

 const routing = RouterModule.forRoot([
      { path: '',      component: DogComponent },
      { path: 'about', component: AboutComponent },
      { path: 'cat', component: HomeComponent}

    ]);

即使我刷新它也能正常工作。所以它认为这部分导致问题,只有路径''可以处理请求。那么我怎样才能将功能添加到其他路线,如/ dog

1 个答案:

答案 0 :(得分:1)

enter code here
Your server model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
  name: { type: String },
  age: { type: Number },
  weight: { type: Number },
  petType: { String }
});
module.exports = mongoose.model('Pet', schema);
// if your just starting to develop your application, I advice you to
// create a file pet-seed.js in your model. To run it, node pet-seed.js so you can edit your pets anytime. // Sorry, I don't know anything about pets..
var Pet = require('./pet'); 
var mongoose = require('mongoose');
mongoose.connect('localhost:27017/yourDBName);
var pets = [
  new Pet({
    name: 'John',
    age: 2,
    weight: 10,
    petType: 'dog'
  }),
 new Pet({
   name: 'Tom',
   age: 3,
   weight: 15,
   petType: 'cat'
  })
];
var done = 0;
for(var i=0; i<pets.length; i++)
  pets[i].save(function(err, result) {
    done++;
    if(done == pets.length)
      exit();
  }
}
function exit() {
  mongoose.disconnect();
}
// Create a folder named DATA
// Create a Pet class
export class Pet {
  constructor(public name: string, public age: number, public weight: number, petType: string, public petId: string){}
}
//Your DATA service and other import files..
import { Pet } from './pet';
@Injectable()    
export class DataService {
  constructor(private _http: HTTP){}
  getPets(){
    return this._http.get('http://localhost:3000/pets')
      .map.response => {
        const data = response.jason().docs; //from server: jason(docs)
        let objs: any[] = [];
        for(let i=0; data.length; i++){
          let aPet = new Pet(data[i].name, data[i].age, data[i].weight, data[i].petType, data[i]._id);
          objs.push(aPet);
        }
        return objs; //To get access at Pet Component;
      })
      .catch(error=>Observable.throw(error.jason()));
  }
}
//Your PetList component
import { Component, OnInit } from '@angular/core';
import { Pet } from './pet';
import { PetDetailComponent } from './pet-detail.component';
import { DataService } from './data.service';
  @Component({
    moduleId: module.id,
    selector: 'rb-pet-list',
    templateUrl: 'pet-list.component.html',
    directives: [PetDetailComponent]
  }); 
  export class PetListComponent implements OnInit {
  pets: Pets[];
  constructor(private: _dataService: DataService){}
    ngOnInit() {
    this._dataService.getPets()
      subscribe(
        pets=>{ this.pets = pets; 
                console.log(pets); // an array of pet objects..
      });
  }
}
//pet-list.component.html
<rb-pet-detail *ngFor="let pet of pets" [pet]="pet"></rb-pet-detail>

//pet-detail.component.html
<ul *ngIf="pet">
  <li>Name: {{pet.name}}</li>
  <li>Age: {{pet.age}}</li>
  <li>Weight: {{pet.weight}}</li>
  <li>Type: {{pet.petType}}</li>
</ul>
//lets make this more interesting..
//Create a PetDetailComponent
import {Component, Input} from '@angular2/core';
import { Pet } from './pet';
  @Component({
    moduleId: module.id,
    selector: 'rb-pet-detail',
    templateUrl: 'pet-detail.component
  })
  export class PetDetailComponent {
    @Input() pet: Pet; //declaring a pet object..
  }
}