Angular 4 how to request a web page content as a json object

1.7k views Asked by At

I am trying to request a web page with a http call and harwest the data.

I could avoid the cross-origin with a chrome plug-in but still when I make the request, the response is always "null".

How could I fetch a html page inside my angular app as a json object ?

ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('http://www.hurriyet.com.tr/gundem/').subscribe(data => {

        this.results = data;
    });
}
2

There are 2 answers

0
danday74 On BEST ANSWER

You should make sure the request URL ends with .json such as:

http://www.hurriyet.com.tr/gundem/gundem.json

This will sort the mime type out automatically. Something like this:

this.http.get('http://www.hurriyet.com.tr/gundem/gundem.json').subscribe(data => {
  // Read the result field from the JSON response.
  this.results = data['results'];
});

You may also need to use data.json() in your promise resolution code.

0
ssuperczynski On
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SomeService {

    constructor(private http: Http) {}

    getItems() {
        return this.http.get('http://www.hurriyet.com.tr/gundem/gundem.json')
            .toPromise()
            .then(res => <Type[]> res.json().data)
            .then(data => { return data; });
    }
}

export interface Type {
    id?;
    title?;
}

app.component.ts

import {SomeService} from './some.service';
export class AppComponent implements OnInit {

  constructor(private someService: SomeService) {
  }

  ngOnInit() {
    this.someService.getItems().then(rows => this.rows = rows);
  }
}