Angular 2,MEAN Stack:接收JSON而不是HTML [英] Angular 2 , MEAN Stack : Receiving JSON instead of HTML

查看:101
本文介绍了Angular 2,MEAN Stack:接收JSON而不是HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向 Angular 2 Full Stack回购添加一条名为"dog"的路由命令行中没有错误,并且表中的数据加载正常

I'm adding a route to Angular 2 Full Stack repo named " dog" there is no error in command line and data loades fine in table

有2个组件

cat:HomeComponent,路径''

cat : HomeComponent , path ' '

dog:DogComponent,路径"/dog"

dog : DogComponent , path '/dog'

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

but when i refresh the page i get the raw JSON instead of HTML

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,但它认为您可以忽略它

I included dog.component.ts but it think you can ignore it

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)添加功能?

and it works okay even after i refresh it. so it think this part is causing the problem and only path '' can handle the request. so how can i add functionality to other routes like /dog ?

推荐答案

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..
  }
}

这篇关于Angular 2,MEAN Stack:接收JSON而不是HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆