$ http GET请求仅在刷新页面时有效

时间:2018-04-17 14:22:47

标签: angularjs mongodb

我有一个连接到MongoDB的AngularJS应用程序。我有从数据库中提取的文章,然后将其重复到文章页面上。我有一个带有Read More ...的按钮,可以将用户带到特定文章。当单个文章视图变为活动状态时,我向数据库发出get请求以获取article._id。 get请求仅适用于页面重新加载,而不是在激活视图时。请参阅下面的代码......

AngularJS控制器

app.controller('ArticleViewController', ['$scope', '$location', '$http', '$routeParams', '$window', function($scope, $location, $http, $routeParams, $window){
// $window.location.reload();

let id = $routeParams.id;

console.log(id);

$http({
    cache: true,
    method: 'GET',
    url: '/:id'
    params: { id }
}).then(function successCallback(res) {
    $scope.article = res.data;
}).catch(function errorCallback(err) {
    if (err) {
        alert('THERE WAS AN ERROR WITH THE DATABASE');
    }
});

}]);

有趣的是,我正在获取routeParams.id,因此部分控制器正在运行。此外,当我取消注释$ window.location.reload时,文章会加载,但它只是将JSON对象加载到浏览器窗口中。提前感谢您的帮助。

使用Express和Mongoose Schema进行路由

router.get('/:id', function(req, res, next){
Article.findById(req.params.id, function(err, article){
        if(err) {
        return err;
     } else {
        console.log(article);
        res.json(article);
   } 
});
});

Mongoose Schema

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

var articleSchema = new Schema({
image: String,
title: String,
about: String,
article: String,
id: String

});

var Article = mongoose.model('Article', articleSchema);

module.exports = Article

Nodejs w / Express

'use strict'
const express = require('express');
const path = require('path');
// const api = require('api');
// const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const request = require('request');
const mongoose = require('mongoose');
// const logger = require('morgan');

const env = require('./env');
const routeMw = require('./public/middleware/routing.mw');

let article = require('./public/routes/article')
let guide = require('./public/routes/guide')

const app = express();
const clientPath = path.join(__dirname, "./public");

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

app.use('/article', article);
app.use('/guide', guide)
app.use('/article/:id', article);

1 个答案:

答案 0 :(得分:0)

您在http请求中有syntex错误问题。 你需要更改parms paramiter我认为show。

app.controller('ArticleViewController', ['$scope', '$location', '$http', '$routeParams', '$window', function($scope, $location, $http, $routeParams, $window){
// $window.location.reload();

let id = $routeParams.id;

console.log(id);

$http({
    cache: true,
    method: 'GET',
    url: '/:id'
    params:{"id": id}
}).then(function successCallback(res) {
    $scope.article = res.data;
}).catch(function errorCallback(err) {
    if (err) {
        alert('THERE WAS AN ERROR WITH THE DATABASE');
    }
});

}]);