My ionic project is connected to a RESTful API so every time if I want to open my project in the browser so before typing “ionic serve”, first I have to type “node index.js” on the API project which is in another folder, not in the same of ionic project. How can I fix that? and make the node index.js automatic every time I type ionic serve. Since I’m in the progress of making a .apk file.
the restful API base url
http://localhost:3000/
the ionic project base url
http://localhost:8100/
I do one of two things here.
First, during initial development, I create mock classes inside the client for all the services that talk to backend APIs. This completely eliminates the need to even have the API, and I frequently find that what I thought I needed out of the API at the beginning ends up not bearing a whole lot of resemblance to what I actually end up needing after I’ve built much of the frontend.
Secondly, once I do need to have a functioning backend, I put it into a container (I use docker for this purpose, but if you like podman or something, fine).
Not sure what a mock class is but I’ve created this:
api.service.ts
api_URL = “http://localhost:3000”;
getProductByName(Name):Observable{
return this.http
.get(this.api_URL +“/products/” + Name)
}
index.js node folder
//GetAProductByName
app.get(‘/products/:name’, (_req, _res) => {
mysqlConnection.query(“SELECT * FROM Products Where Name Like ?”, [_req.params.name], (err, rows, _fields) => {
if (!err)
_res.send(rows);
else
console.log(err);
})
});
Maybe I should have asked: How to set the express server to run automatically/ all the time?
interface Employee {
id: string;
name: string;
}
interface EmployeeServiceFacade {
fetchAllEmployees(): Observable<Employee[]>;
employeeById(id: string): Observable<Employee | null>;
updateEmployee(e: Employee): Observable<string>;
}
class EmployeeService implements EmployeeServiceFacade {
constructor(private http: HttpClient) {}
fetchAllEmployes(): Observable<Employee[]> {
return this.http.get<Employee{]>("/api/employees");
}
... actual implementations of other methods
}
class MockEmployeeService implements EmployeeServiceFacade {
mockEmployees: Employee[] = [
{id: "001", name: "Arianna Allen"},
{id: "002", name: "Billy Bogart"},
{id: "003", name: "Candace Cooper"},
];
fetchAllEmployees(): Observable<Employee[]> {
return of(this.mockEmployees);
}
... etc
}
class AppModule {
...
providers: [
// comment out one of the following two lines to swap back and forth between
// mocked and actual service
{provide: EmployeeService, useClass: MockEmployeeService},
EmployeeService,
];
}
class EmployeePage {
constructor(private svc: EmployeeService) {
// this class has no clue whether it is getting a real or mock service, and therefore
// can be thoroughly developed and tested without needing a production deployment
// environment
}
}