Kearney Taaffe Kearney Taaffe - 12 days ago 4
Node.js Question

Aurelia Content Management tutorial API - Cannot read property 'then' of undefined

I'm learning Aurelia. In following the content management tutorial, it suggested that I try to make a real API call. So, I'm trying just that.

I'm made a simple node server that returns a JSON array of objects on GET

// test_server.js
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

var contacts = [
{
id: 1,
firstName: 'John',
lastName: 'Doe',
email: 'jdoe@gmail.com',
phoneNumber: '867-5309'
},
{
id:2,
firstName:'John',
lastName:'Doh',
email:'jdoh@gmail.com',
phoneNumber:'867-5308'
},
];

const server = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET');
res.setHeader('Access-Control-Allow-Headers', '*');

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(contacts));
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});


In the
aurelia_project/aurelia.json
file, I added the following

"dependencies": [
..,
"aurelia-http-client",
...
]


Then, I created a new web API file.

//new-web-api.js (es2015)
import {HttpClient} from 'aurelia-http-client';

export class NewWebAPI {

getAllContacts() {
var client = new HttpClient();

client.get('http://127.0.0.1:3000')
.then(data => {
console.log(data.response)
return new Promise(resolve => JSON.parse(data.response));
})
.catch(err => {
console.log('failed to get a response :-(')
});
}
}


Here is the updated
contact-list.js
file,

// src/contact-list.js
import {NewWebAPI} from './new-web-api';

import {EventAggregator} from 'aurelia-event-aggregator';
import {ContactUpdated, ContactViewed} from './messages';

export class ContactList {

static inject() {
// we declare an "inject" static method that returns an array of constructor
// dependencies
return [NewWebAPI, EventAggregator]
};

constructor(api, ea) {
this.api = api;
this.contacts = [];

/*ea.subscribe(ContactViewed, msg => this.select(msg.contact));
ea.subscribe(ContactUpdated, msg => {
let id = msg.contact.id;
let found = this.contacts.find(x => x.id === id);
Object.assign(found, msg.contact);
});*/
}


created() {
this.api.getAllContacts().then(contacts => this.contacts = contacts);
}

select(contact) {
this.selectedId = contact.id;
return true;
}
}


I'm getting data back from the server (the console.log in
new-web-api
proves it.

I'm just unsure of how to return a promise to the
contact-list
module.

Thanks in advance.

Answer

JSON.parse doesn't return a promise, it just returns the object parsed from the JSON, so you just need to return the parsed JSON from the promise, and then return the promise itself in getAllContacts. See below:

//new-web-api.js (es2015)
import {HttpClient} from 'aurelia-http-client';

export class NewWebAPI {

    getAllContacts() {
        var client = new HttpClient();

        return client.get('http://127.0.0.1:3000')
            .then(data => {
                console.log(data.response)
                return JSON.parse(data.response);
            })
            .catch(err => {
                console.log('failed to get a response :-(')
            });
    }
}

Everything else should be able to stay the same. Let me know if this helps.

Comments