Angular 2 http request with Access-Control-Allow-Origin set to *

I’m using angular2 and typescript.

I’m trying to post to my mail chimp subscription list.

My code so far:

 constructor(router: Router, http: Http){   
      this.router = router;

      this.http = http; 
      this.headers = new Headers();
      this.headers.append('Content-Type', 'application/json');
      this.headers.append('Access-Control-Allow-Origin', '*');

  subscribe = () => {
        var url = "" +;
        this.isSuccess = false;

        this.http.request(url, this.headers).subscribe(response => {
           this.isSuccess = true; 

This is the error I get in my console:

enter image description here

I get this error now: Uncaught SyntaxError: Unexpected token <

Current code below:

export class Footer{
  email: string = "";
  router : Router;
  http : Http;
  jsonp: Jsonp;
  isSuccess: boolean = false;

  constructor(router: Router, jsonp: Jsonp, http: Http){   
      this.router = router;
      this.http = http; 
      this.jsonp = jsonp;

  subscribe = () => {
        var url = "" +;
        this.isSuccess = false;

        this.jsonp.request(url).subscribe(response => {
           this.isSuccess = true; 

Angular2 HTTP: Uncaught SyntaxError: Unexpected token < polyfills

So Im practicing http post and get methods of Angular2 from YouTube tutorial and I cant figure out the problem
Here is my index.html files:

    <title>MyTodo App</title>

<script src="node_modules/es6-shim/es6-shim.js"></script>
<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/"></script>
<script src="node_modules/angular2/bundles/"></script>


        packages: {
            app: {
                format: 'register',
                defaultExtension: 'js'
  .then(null, console.error.bind(console));

This is http service file:

import { Injectable } from 'angular2/core';
import { Http } from 'angular2/http';
import 'rxjs/add/operator/map' ;

export class webhttpservice{

constructor(private http : Http){}

   return this.http.get('')
              .map(res => res.json());

Here is app.ts file:

import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { webhttpservice } from './httpService';
import { HTTP_PROVIDERS } from 'angular2/http';

selector : 'http-comp',
template : `

<button (click) = 'reqfunction()'>Get Request</button>
<button>Post Request</button>

providers : [webhttpservice]
export class httpcomponent{

constructor(private var1: webhttpservice){}
                data => this.getdata = JSON.stringify(data),
                error => alert(error),
                () => console.log('Finished')



bootstrap(httpcomponent, [HTTP_PROVIDERS]);

These are the original errors Im getting

>Uncaught (in promise) TypeError: object is not a constructor(…)  
httpService:1 Uncaught SyntaxError: Unexpected token <__exec @ 
Uncaught SyntaxError: Unexpected token <
Evaluating http://localhost:3000/httpService
Error loading http://localhost:3000/app.jsrun
@ angular2-polyfills.js:138zoneBoundFn @ angular2-

Angular2 @Input and http.get

I’m missing something when passing data from a component to another component. I use @Input to pass the data, that i get from an http.get request. The thing is, i get an error while trying to access an attribute from the passed input while the request hasn’t been resolved.

import {Component} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Pagination} from './pagination';

    selector: 'news',
    templateUrl: 'app/news.html',
    viewProviders: [HTTP_PROVIDERS],
    directives: [Pagination]
export class News {

    news = [];

    pagination: Pagination;

    constructor(http: Http) {
            .map(res => res.json())
            .subscribe(news => = news);

import {Component, Input} from 'angular2/core';

    selector: 'pagination',
    templateUrl: 'app/pagination.html'
export class Pagination {
    // page: int = 1;

    @Input() config;

    constructor() {
        // = this.config.number;

Page {{}} generates an error on load. But doing {{config}} seems to work though.

Any ideas ?


angular2 CLI HTTP not found error

I’ve created a new angular2 application using the angular-cli. Now I was trying to get the data from an API using HTTP. The code I’ve written:


import { Injectable } from '@angular/core';
import { Movie } from './movie';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

My atom editor gives error on @angular/http line. So, I’ve manually installed angular2 using npm install angular2 on my project folder and then modify that error generated line like this:

import { Http, Response } from 'angular2/http';

BUt now my console is showing:

“NetworkError: 404 Not Found –

I’ve added in my index.html page the following script:

<script src=""></script>

and in my package.json files dependencies "angular2": "2.0.0-beta.17",.
still the same error.

Anyone have any clue? I’m a newbie in angular2. So, any help or suggestion is highly appreciated.

Angular2 rc1 : Http subscribe issue

I am trying implement my http service component using below link

My service component

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

export class DemoService {

  constructor(private http:Http) { }

  // Uses http.get() to load a single JSON file
  getFoods() {
    return this.http.get('').map((res:Response) => debugger; res.json(););

  // Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
  // The entire operation will result in an error state if any single request fails.
  getBooksAndMovies() {
    return Observable.forkJoin(
      this.http.get('').map((res:Response) => res.json()),
      this.http.get('').map((res:Response) => res.json())


And parent component

import {Component, ViewChild} from '@angular/core';
import {DemoService} from './demo.service';

    selector: 'my-app', //<----the element defined in the index.html
    template: `
    <h1>Angular2, Hello {{name}}</h1>
    <div *ngIf="data_error">An error occurred while loading the data!</div>

export class AppComponent { 
    name: string;
    data_error: Boolean = false;
    public foods: any;
    public books: Array<string>;
    public movies: Array<string>;

    modal: ModalComponent;

    constructor(private _demoService: DemoService){ = "ANIL";

    close() {

    open() {;

  getFoods() {
      (data:any[]) => { 
        //alert(data[0]); **this 'data' is undefined** :(
        this.foods = data

      err => { this.data_error = true }

  getBooksAndMovies() {
      data => {
        this.books = data[0];
        this.movies = data[1];

} // <--- we need to export the class AppComponent. 

Observable.forkJoin() can be subscribed successfully but could not understand what is the issue with http.get().map()

Please help!!!

Angular2 Response for preflight is invalid (redirect) from some GET requests

I am using Angular2, Communicating with a rest API, settings the header like so:

import { Headers } from '@angular/http';

export const contentHeaders = new Headers();
contentHeaders.append('Accept', 'application/json');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Authorization', localStorage.getItem('id_token'));

Get request like items/ and POST request works, but when making GET requests for one item, like: items/579212a6541d5626732619c3 the server respond with a server error Response for preflight is invalid (redirect)

I thought those get requests are the same, but maybe they are not ? Any solutions ?

angular 2 create custom variables to perfomm CRUD on specified url

below is a model which includes some http request. My question is can i hab services instantiated through instantiating a new class object?

export class DbHttp {

    private path:string;

    constructor(private path:string, private customService:CustomService){}

        return this.customService.create(this.path, data)

        return this.customService.getAll(this.path)

What I want to achieve is a shortcut to perform http request on customized url. ideally the syntax should be something like this

public dbAccessTodo = this.service.access('todo')
//access is a method which returns an object with builtin CRUD functions for a Base_Url+'todo'



angular2, http with credentials. Can't add cookies

I Have been trying for some time to get past this problem. I need to connect to a remote server with my credentials, I am able to this with no problems. Next I need to perform a get for some resource on the server, from my experience in angular 1 I need to use the credentials I got from the login stage I just can’t seem to get the right way to do it..

This is how I preform my login:

import { Injectable } from 'angular2/core';
import { IjobCard } from '../jobCard/jobCard';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
import { Icredentials } from './credentials';

export class LoginService {
    private _loginUrl = 'MyUrl/Login';
    loginCred: Icredentials = {
        "filed1": "dummy1",
        "filed2": "dummy2", 
        "filed3": "dummy3"

    constructor(private _http: Http){


    login(): Observable<any>[] {
        return, JSON.stringify(this.loginCred))
            .map((response: Response) => <any[]>response.json())


    private handleError(error: Response){
        return Observable.throw(error.json().error || 'Server error');

And this is how I am trying to execute my next get:

import { Injectable } from 'angular2/core';
import { IjobCard } from './jobCard';
import { Http, Response, Headers } from 'angular2/http';
import { Observable } from 'rxjs/Observable';

export class JobCardService {
    private _jobCardUrl = 'MyUrl/SomeGet';
    constructor(private _http: Http) {

    getJobCard(): Observable<any>[] {
        var myHeders = new Headers();
        myHeders.append('Content-Type', 'application/json');
        return this._http.get(this._jobCardUrl, { headers: myHeders, withCredentials: true} )
        .map((response: Response) => <any[]>response.json())


    private handleError(error: Response){
        return Observable.throw(error.json().error || 'Server error');

Sadly, what I get back is an 401 unauthorised, I already tried many other methods based on the search result Google provides… no luck.

I was able to connect to the same service from an angular 1 app and by using postman…


Ok, I tried following John Baird answer to my question but I couldn’t make it work. But I got some new clues to what the problem could be:

  • The server respose has the following headers:

    Access-Control-Allow-Credentials: true
    access-control-allow-headers: content-type,
    accept access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
    access-control-allow-origin: http://localhost:3000

  • I also found out that in my angular 1 project the request to contains a header of cookie like so:

    Cookie: B1SESSION=GLWzfesg-sscK-yAH9-PH4m-99r5hCrOdddh; ROUTEID=.node0

    but my angular2 project did not, even when using the withCredentials flag.

  • I tried solving it by following some ideas from :
    by adding this to my main:

    class MyBaseRequestOptions extends BaseRequestOptions {
        headers: Headers = new Headers({
            'X-Requested-With': 'XMLHttpRequest'
        withCredentials: boolean = true;
    bootstrap(AppComponent, [
        provide(RequestOptions, {useClass: MyBaseRequestOptions}) ]);

    but still no cookies are sent with my request.

Is this the right path? Any more ideas to try?

Angular 2 : No provider for ConnectionBackend

Get this “No provider for ConnectionBackend!” error when trying to use http with a promise.


// ... tl;dr import a bunch of stuff



// ... tl;dr import a bunch of stuff

 declarations: [
  providers: [
  imports: [
  bootstrap: [MyComponent]


import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {MyService} from './../services/myService'
import {Post} from './post';

  templateUrl: 'post.component.html',
  styleUrls: ['post.component.css']
export class MyComponent implements OnInit {
  post: Observable<Post>;
  postId : Number;

  constructor(private route: ActivatedRoute, private router: Router, private service:MyService) {


  ngOnInit() {
    this.route.params.subscribe(params => {
      this.postId = +params['id']; = this.service.getPostById(this.postId);



import {Injectable} from "@angular/core"
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Post} from './../post/post';
import 'rxjs/Rx'

export class MyService {

    endpoint_url:String = "";

    constructor(private http: Http){

    getPostById (id:Number) : Observable<Post> {
        return this.http.get(this.endpoint_url + id.toString()).map(res => res.json());

All looks good but then I get this error:

error_handler.js:51Error: Uncaught (in promise): Error: Error in ./MyComponent class MyComponent_Host - inline template:0:0 caused by: No provider for ConnectionBackend!
at resolvePromise (zone.js:429)
at zone.js:406

And here is the docs for ConnectionBackend. I think I just need to add something to providers in myModule?