P
P
Programep2017-08-08 23:06:41
JavaScript
Programep, 2017-08-08 23:06:41

How to make a GET request in angularjs 2 to localhost?

Good afternoon! Please tell me what I'm doing wrong.
1. Created a service on angularjs2:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class EventsService {  
  private _url: string = "http://localhost:4200/api/data.json";		
  constructor(private http: Http){}      
    getData(){ 		
        return this.http.get(this._url)
        .map( (response: Response) => response.json() );
    }
}

2. I run the command in the project directory: npm start. 3. The project works in the
browser at localhost:4200 .
But in the browser console there is an error when getting the localhost:4200/api/data.json file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/data.json</pre>
</body>
</html>

My guess is that npm start doesn't start a full server.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
agladkov, 2017-08-17
@Programep

1. First you need to understand how HTTP works. This is a client-server architecture.
2. Angular runs in the browser - the client.
3. npm start (ng serve) - starts the simplest web server that serves static files with Angular code to work in the browser.
The running web server does not have a localhost:4200/api/data.json file If you want the test web server to return a
static data.json file, then you need to dig towards "ng server static files"
-cli.json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question