Angular 2 - Error: Unexpected token < in Http request

I encountered a JavaScript error in my browser while working with the following code:

Uncaught SyntaxError: Unexpected token <

The error disappears when I remove

constructor(private _http:Http) { }
from image.service.ts.

Could it be that I am incorrectly using http? How can I create an http service that simply returns JSON data?

App.compontent.js:

import {Component, OnInit} from 'angular2/core';
import {Image} from './image';
import {ImageDetailComponent} from './image-detail.component';
import {ImageService} from './image.service';

@Component({
    selector: 'my-app',
    directives: [ImageDetailComponent],
    providers: [ImageService],
    template: `
    <h1>{{title}}</h1>
    <h2>Choose your security image</h2>
    <button (click)="getImageData()">Get Image Data!</button>
    <ul class="images">
      <li *ngFor="#image of images"
        (click)="onSelect(image)">
        <img class="image-responsive" src="{{image.imageurl}}">
      </li>
    </ul>
    <my-image-detail [image]="selectedImage"></my-image-detail>
    `
})

export class AppComponent implements OnInit{
  title = 'Authenticate';
  images: Image[];
  selectedImage: Image;

  constructor(private _imageService: ImageService) { }

  getImages() {
     this._imageService.getImages().then(images => this.images = images);
   }
   ngOnInit() {
     this.getImages();
   }

  onSelect(image: Image) { this.selectedImage = image; }
}

image.service.js:

import {Image} from './image';
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable()
export class ImageService {

  constructor(private _http:Http) { }
  items: Array<Image>;

  getImageData() {
    this._http.get('http://localhost/pincode/api/src/1.0/get/images.php')
      .map(res => res.json())
      .subscribe(
        data => this.items = data,
        err => this.logError(err),
        () => console.log('Got Images')
      );
    return this.items;
  }

  logError(err) {
    console.error('There was an error: ' + err);
  }

  getImages() {
     return Promise.resolve(this.getImageData());
   }

}

Answer №1

It appears you may have overlooked including the HTTP JS file necessary for Angular2:

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script> <-----

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Develop your project with Angular 2 using the powerful Angular CLI build tool

Hello there! I am new to Angular 2 and recently developed a small project with the help of angular-cli for packaging. The dist folder was generated successfully. However, when I deployed the app to the server and tried to access the index.html page, it co ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Issues with Angular updating the *ngFor Loop

I'm looking to showcase a lineup of upcoming concerts in my HTML, sourced from a web API (which is functioning correctly). The API is encapsulated within a ConcertService: @Injectable({ providedIn: 'root' }) export class ConcertService { ...

How can I specify the type of a property in Typescript?

Looking for a solution: type WithRequiredProperty<Type, Key extends keyof Type> = Omit<Type, Key> & { [Property in Key]-?: Type[Property]; }; export type MessageWithMdEnforced = WithRequiredProperty<IMessage, 'md'>; ex ...

Convert an observable into an array so that it can be used to create a Google chart

I've been working with Angular CLI 6 and Angularfire2, and my code is functioning well to display data in the template using a typical ngFor loop and an asynchronous pipe. However, I also need to utilize the data for a Google graph, which requires dat ...

Tips for resolving the issue: Encountered an unexpected token < when parsing JSON data at position 0 using the JSON.parse function

I encountered an error when working on the code mentioned in this post. After removing .json() from response.json() in my code snippet below, the error message changed: return this.http.post('http://localhost:3000/sign-up', body, {headers: head ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

What is the best way to publish an Angular 5 project within a Laravel application?

Can you provide guidance on deploying the Angular 5 project build within Laravel? I have successfully deployed the build files in Laravel, and everything seems to be working fine. However, when I refresh the page after routing to a different page, a 404 ...

The form submission is yielding an incorrect value

When creating multiple form groups, the issue arises where submitting one form returns the value of the last entered form. export class ExpansionOverviewExample { panelOpenState = false; tables: string[] = ['one', 'two', 'three ...

Error encountered during password reset in Auth0

I am currently working with Angular 2 and using lock version 10.8 in an attempt to implement a feature that allows users to change their password. I've been experimenting with the following method, which involves calling the Management API. In this me ...

Differences between Angular MSAL Library's acquireTokenRedirect and acquireTokenPopup functions resulting in errors

Currently, I am utilizing the msal angular library to handle logins and backend API communication in order to obtain tokens and access a dashboard. While trying to implement the option of using redirect instead of popup for signing in or obtaining a token, ...

TouchEnd and MouseUp events

What causes both the TouchEnd and MouseUp events to be triggered when using a mobile device? We need to test our app in both the browser and on mobile devices for debugging purposes, which is why we use TouchEnd & MouseUp. The issue arises when I bui ...

Ways to refresh Prism.js upon ngModel update in Angular 5

Currently, I am in the process of developing a CMS and facing an issue with re-rendering Prism.js to display syntax highlighting in the preview whenever there is a change in the body of the article. Below is the template code: <textarea [(ngModel ...

Implementing a custom loading spinner in Angular 2

One of the tasks I have is to implement a loading spinner whenever my data is still being processed. Here is an example of my service: ... constructor(private _http:Http) { } getDataFromApi() { return this._http.get('https://api.punkapi.c ...

What is the best way to incorporate or reference an existing AngularJS project in a new project?

https://i.stack.imgur.com/2dkC0.png The image suggests that Angular app1 serves as a shared module for both app2 and app3. Is there a way to inject app2 and app3 into the common module? If direct injection is not possible, does anyone have suggestions on ...

Is there a specific method for conducting a production build using AngularCLI rc.1?

Just recently upgraded to angular-cli version 1.0.0-rc1 by following the guidelines provided on the wiki. The application functions properly when I execute ng serve. Similarly, the app works as expected when I run ng build. However, encountering an issu ...

Beyond Cross field validation within the Angular Validator

One issue I am facing with my form is that some fields are dependent on others. I want to validate the control when the value changes. I am aware of the global validator on formgroup, but I have reasons for not wanting to use it. Let's say a user ent ...

The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle I've managed to create the underline effect on the navigation links when the user hovers over them. However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as l ...

Bring in the module for DecompressionStream

I'm encountering an issue in my React Typescript app where I am seeing the following error message: webpack compiled with 1 warning ERROR in src/App.tsx:30:21 TS2304: Cannot find name 'DecompressionStream'. 28 | const enc = new TextEncod ...

Is it possible to reset the attributes of a container's children using a renderer?

Within a container, there are dropdowns, multiple selects, and quantity selections. When a button is clicked, I aim to reset the state of the component. https://i.stack.imgur.com/TY5un.png <input #select type="checkbox" value="somevalue"/> The ...