3

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?.

2 Answers 2

6

You need to append Accept headers to your get request in order for Firefox to render the json that comes back. I found this after searching quite a bit and came across this https://brockallen.com/2012/04/27/change-firefoxs-default-accept-header-to-prefer-json-over-xml/ which led me down the path of adding the headers

    ngOnInit() {
    let headers = new Headers();
    headers.append('Accept', 'q=0.8;application/json;q=0.9');
    return this.http.get(this.url, { headers: headers } ).map(res => {
              return res.json();
            }).subscribe((response) => { console.log(response) });
}
Sign up to request clarification or add additional context in comments.

2 Comments

I just want to give you a big ol hug. My angular2 application wasn't working on FF and I could not figure out why. It was the 'Accept': 'application/json' header. Thank you so much!
Oh man, I know these comments are frowned upon, but thank you, this saved me. Huge digital high 5 for you!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.