Rumes Shyaman Rumes Shyaman - 6 months ago 139
Ajax Question

angular 2 ajax call getting error "EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

I'm creating app using angular2 and i need to get weather from yahoo weather. I try to do it using http get method but it's give me a error.

import {Component,OnInit,} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';

@Component({
templateUrl:'app/contact/contact.html',
})

export class ContactComponent{
constructor (private http: Http) {}
public url:string= "http://weather.yahooapis.com/forecastjson?w=2295424";

ngOnInit(url:string) {

return this.http.get(url).map(res => {
return res.json();
}).subscribe((response) => { console.log(response) });

}

}


Error I get is


EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data


can anyone help me with this?.

Answer

I think the payload of your response isn't actually JSON. That's why Angular can't parse it. You could have a look within the Network tab of the Chrome developer tools for example for more hints.

I try your request (http://weather.yahooapis.com/forecastjson?w=2295424) and I got a 404 response with an HTML payload (and not a JSON one).

A strange thing in your code is the parameter you provide to the ngOnInit method. You should try something like that:

ngOnInit() { 
    return this.http.get(this.url).map(res => {
              return res.json();
            }).subscribe((response) => { console.log(response) });
}

Hope it helps you, Thierry