Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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