2

I am trying to do a simple GET request with Http in Angular 2, following this TUTORIAL and some other more up to date resources.

After successfully injecting the http component, I wrote the following code

 constructor(@Inject(Http) /* remove @Inject once @Injectable works */ public http:Http){
        http.get('https://api.travis-ci.org/config').toPromise().then((response => console.log(response.json().data) )
        //     .map(res => res.text())
        //     .subscribe(
        //     data => console.log(data),
        //     err => console.error(err),
        //     () => console.log('Random Quote Complete')
        // );
    }

As you can see there are a lot of comments as I have tried several combinations. I am getting these errors

http.get(...).map is not a function(…)

if I try to use map

Request header field X-XSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.

for anything else.. (toPromise) for example.

how can I make it work?

If I use fetch, the call works.. so it has to be something in angular.

guy mograbi
  • 27,391
  • 16
  • 83
  • 122

2 Answers2

2

There is no method map() associated with 'Promise'. Check the link Angular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]

I solved your issue. Here i used Observer/subscriber pattern. You just check the following code:

rxjs-operators.ts

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

travis-service.ts

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

@Injectable()
export class TravisService {
  constructor (private http: Http) {}

  getData (): Observable<any> {
    return this.http.get('https://api.travis-ci.org/config')
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server   error';
    return Observable.throw(errMsg);
  }
}

And you can subscribe the data using the below code.

travis.component.ts

import { Component, OnInit, } from '@angular/core';
import { TravisService }        from './travis-service';

@Component({
  selector: 'travis-app',
  templateUrl: 'app/travis-app.component.html',
  providers: [TravisService]
})
export class TravisComponent implements OnInit {
    errorMessage: string;
    constructor(private travisService: TravisService) { }
    ngOnInit() {

        this.travisService.getData().subscribe(
            data => { 
                console.log(data);
            },
            error =>  this.errorMessage = <any>error
        );
    }

}
Community
  • 1
  • 1
Libu Mathew
  • 2,976
  • 23
  • 30
  • It was enough to add Observable. Thanks! Can you please add this specific line to the answer and mark the rest as TLDR? It is actually mentioned by angular's quickstart, but hard to notice due to all the clutter of information on their page. `import { Observable } from 'rxjs';` is in https://angular.io/docs/ts/latest/tutorial/toh-pt6.html – guy mograbi Oct 07 '16 at 04:43
  • I checked. `import { Observable } from 'rxjs';` not worked for me. But when i add `import { Observable } from 'rxjs/Rx';` it works. Iam using rxjs-5.0.0-beta.12 version from npm. – Libu Mathew Oct 07 '16 at 05:01
1

You can try

export class NoXSRFStrategy implements XSRFStrategy {
  configureRequest(req: Request) {}
}
@NgModel({
  providers: [{provide XSRFStrategy, useClass: NoXsrfStrategy}],
  ...
})

you shouldn't use this in production. Travis seems to miss Access-Control-Allow-Headers "X-XSRF-TOKEN"

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567