Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Building a MEAN Application Going MEAN with Express Setting Up an Express API

Why without having a router, Angular doesn't work properly?

I have a simple MeanStack example with a few modification (using templates as static files to store HTML, CSS and webpack scripts) with Angular implemented but even if I just use the root route to display everything, Angular services doesn't make a difference it just loads the content even if I call some random json data route. Here is the example:

src/index.js

'use strict';

var express = require('express');

var app = express();

var data = require('../mock/todos.json');

app.set('views', __dirname + '/templates');
app.use('/', express.static('templates'));

app.use('/', function(req, res) {
    res.json({data:data});
});

app.listen(3000, function() {
    console.log("Serving on port 3000");
});

app/services/data.js

'use strict';

var angular = require('angular');

angular.module('todoListApp')
.service('dataService', function($http) {
    this.helloConsole = function() {
        console.log('This is the data service method');
    };

    this.getTodos = function(callback) {
        $http.get('vdskdsjkfsjdkflsjklfsdjfklsdjkfljsd')
        .then(callback);
    };

    this.deleteTodo = function(todo) {
        console.log("Deleted: " + todo.name);
    }

    this.saveTodo = function(todo) {
        console.log("Saved: " + todo.name);
    }
});

Why is this working? And, would this make a problem for future development?

1 Answer

Without seeing all of your code, I would guess that it is because you're trying to serve both static files in the templates folder, as well as returning the JSON response from data on the root route ('/'). Try changing the route for the data to /api or something.

I see. So I need to use the router to make Angular services differentiate between multiple urls.

Express is setting all the routes/urls. You could use client-side routing on top of that (with Angular), probably using the 'hash' style: http://example.com/app/#/todos