Seeking assistance with a technical issue.
My objective: Make a REST API call to retrieve JSON data and resolve an Angular 2 promise.
ServerAPI built with Node.js/ExpressJS/Lodash
Sample of server.js file:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var data = require('./data.json');
var _ = require('lodash');
var cors = require('cors');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.get('/GetData', function (req, resp) {
if (req.query.search != null) {
var result = _.find(data, function (o) {
return o.value === req.query.search.toLowerCase().trim()
});
return resp.send(result)
}
});
app.listen(1337, function () {
console.log('Listening at Port 1337');
});
Tested by running http://localhost:1337/GetData?search=colorado and successfully returning valid JSON object.
ClientAPI
Service file implementing HTTP request:
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Config} from "../config";
import {SearchResult} from "../models/search-result.model";
import {MockSearchData} from "../mock/mock-search-results";
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiDataService {
constructor(private http:Http) {
}
public performSearchRequest(searchTerm:string,queryType:string):Promise<SearchResult[]> {
return new Promise<SearchResult[]>((resolve, reject) => {
let url = Config.apiBaseUrl + Config.searchApi;
url += "?search=" + searchTerm;
console.log("Your query will be sent to: " + url);
if (searchTerm != "") {
if (queryType == 'mock') {
resolve(MockSearchData);
} else if (queryType == 'api') {
let data = [];
this.http.get(url)
.map(resp => resp.json())
.subscribe(getData => data = getData);
resolve(data);
} else {
reject("No matching query type found.");
}
} else {
reject("Please provide a search term.");
};
});
}
}
The resolution of mock data, retrieved locally within the ClientAPI, is functioning as expected. However, I am facing challenges in making the api query type work properly.
The Angular application initializes without errors and executes the http.get method smoothly. Upon checking the network tab in the developer tools, it confirms that an HTTP request was made and returned the desired valid JSON response. Despite this, the table where the data should be displayed remains empty.
What could be causing this issue?