wowiamhere wowiamhere - 25 days ago 14
HTTP Question

AngularJs 2 Http CONNECTION ERROR

AngularJs 2 with Webpack.

I am not able to connect to NYT Api.

ALL ENDOPOINTS TESTED AND WORKING PROPERLY

AngularJs 2 in production mode:

enableProdMode();


App:

-1 component

-1 Service

All other components working/displaying properly.

No other services on app yet.

Service returns with error: (in console)

error: "Collection 'topstories' not found"


error-from-console

The Service

import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs';

@Injectable()

export class NewsService {

private topStoriesUrl: string = `https://api.nytimes.com/svc/topstories/v2/politics.json`;
// private topStoriesUrl: string = `https://newsapi.org/v1/articles`;

// Injecting Http capabilities
constructor( private http: Http ) {}

// for error handling
private handleError(error: any): Promise<any>{
console.error("FromSERVICE:::---:::--> ", error);
return Promise.reject( error.message || error );
}

getNews(): Observable<any> {

let parms: URLSearchParams = new URLSearchParams();
parms.set("api-key", "184db335652341518bea3e4a5db85494");
// parms.set("source", "associated-press");
// parms.set("apiKey", "e4e2aa62a883464a87547e8de4336f61");

return this.http.get( this.topStoriesUrl, { search: parms } )
.map( (res: Response) => res['articles'] )
.catch( this.handleError );
}
}


The Component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

// service for fetcing news from api
import { NewsService } from '../services/news.service';

@Component({
selector: 'main-news',
templateUrl: '../templates/main-news.component.html'
})

export class MainNewsComponent implements OnInit{

private news: Observable<any>;

constructor(
private router: Router,
private newsService: NewsService
) {}

ngOnInit(): void {
this.newsService.getNews().subscribe( {
next: r => this.news = Observable.of<any[]>(["one"]),
error: err => console.error("From COMPONENT--->", err)
} );
}
}


I have tried this call with both Api from different organizations to get
the same error on the URL resource.

I have tried this same call with said URL with a Ruby script (NET/http) and also directly on the browser address bar, to receive a VALID response on these BOTH cases.

NOT SURE WHY IT FAILS WITH ANGULAR.

HELP!!!

Answer

Turns out I was missing the:

Access-control-allow-origin  

header.
Go figure!
Apparently, it is not added automatically by AngularJs 2.

Thanx