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 = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
        this.isSuccess = false;

        this.http.request(url, this.headers).subscribe(response => {
           console.log(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 = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
        this.isSuccess = false;

        this.jsonp.request(url).subscribe(response => {
           console.log(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:

<html>
<head>
    <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/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>

</head>
<body>

    <script>
    System.config({
        packages: {
            app: {
                format: 'register',
                defaultExtension: 'js'
            }
        }
    });
System.import('app.js')
  .then(null, console.error.bind(console));
</script>
    <http-comp>Loading..</http-comp>
</body>
</html>

This is http service file:

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

@Injectable()
export class webhttpservice{

constructor(private http : Http){}

getfunctionfromapp(){
   return this.http.get('www.google.com')
              .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';

@Component({
selector : 'http-comp',
template : `

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

`,
providers : [webhttpservice]
})
export class httpcomponent{

getdata;
constructor(private var1: webhttpservice){}
reqfunction(){
    this.var1.getfunctionfromapp()
            .subscribe(
                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 @ 
angular2-polyfills.js:138   
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.

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

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

    news = [];

    pagination: Pagination;

    constructor(http: Http) {
        http.get('http://test.com/data')
            .map(res => res.json())
            .subscribe(news => this.news = news);
    }
}

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

@Component({
    selector: 'pagination',
    templateUrl: 'app/pagination.html'
})
export class Pagination {
    // page: int = 1;

    @Input() config;

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

//Pagination.html
Page {{config.total}}

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

Any ideas ?

Thanks

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:

movies.service.ts

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 –
http://localhost:4200/angular2/http/index.js

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

<script src="https://code.angularjs.org/2.0.0-beta.17/http.dev.js"></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

http://www.metaltoad.com/blog/angular-2-http-observables

My service component

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

@Injectable()
export class DemoService {

  constructor(private http:Http) { }

  // Uses http.get() to load a single JSON file
  getFoods() {
    return this.http.get('http://ip.jsontest.com/').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('http://ip.jsontest.com/').map((res:Response) => res.json()),
      this.http.get('http://date.jsontest.com/').map((res:Response) => res.json())
    );
  }

}

And parent component

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

@Component({
    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>
    <div>{{foods?.ip}}</div>
    <div>{{books?.ip}}</div>
    <div>{{movies?.date}}</div>
    <br>
    `

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

    @ViewChild('mymodal')
    modal: ModalComponent;

    constructor(private _demoService: DemoService){
        this.name = "ANIL";
        this.getFoods();
        this.getBooksAndMovies();
    }

    close() {
        this.modal.close();
    }

    open() {
        this.modal.open();
    }

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


      },
      err => { this.data_error = true }
    );
  }

  getBooksAndMovies() {
    this._demoService.getBooksAndMovies().subscribe(
      data => {
        debugger;
        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){}

    create(data:Object):Observable<Response>{
        return this.customService.create(this.path, data)
    }

    getAll():Observable<Response>{
        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'

create(data){
  this.dbAccessTodo.create(data)
}

Thanks!

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';

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

    constructor(private _http: Http){

    }

    login(): Observable<any>[] {
        return this._http.post(this._loginUrl, JSON.stringify(this.loginCred))
            .map((response: Response) => <any[]>response.json())
            .catch(this.handleError);

    }

    private handleError(error: Response){
        console.error(error);
        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';

@Injectable()
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())
        .catch(this.handleError);

    }

    private handleError(error: Response){
        console.error(error);
        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…

*******UPDATE********

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 :
    https://github.com/angular/angular/issues/4231
    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.

main.ts

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

platformBrowserDynamic().bootstrapModule(MyModule);

myModule.ts

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

@NgModule({
 declarations: [
        PostComponent
  ],
  providers: [
    Actions,
    MyService,
    Http
  ],
  imports: [
    ...
  ],
  bootstrap: [MyComponent]
})

myComponent.ts

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';

@Component({
  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.post = this.service.getPostById(this.postId);
    });
  }

}

myService.ts

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

@Injectable()
export class MyService {

    endpoint_url:String = "http://someurl.com/";

    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?