Angular4 如何请求一个网页内容作为一个json对象
Angular 4 how to request a web page content as a json object
我正在尝试通过 http 调用请求网页并获取数据。
我可以使用 chrome 插件避免跨域,但当我发出请求时,响应始终是 "null"。
如何在我的 angular 应用程序中获取 html 页面作为 json 对象?
ngOnInit(): void {
// Make the HTTP request:
this.http.get('http://www.hurriyet.com.tr/gundem/').subscribe(data => {
this.results = data;
});
}
您应该确保请求 URL 以 .json 结尾,例如:
http://www.hurriyet.com.tr/gundem/gundem.json
这将自动对 mime 类型进行排序。像这样:
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'];
});
您可能还需要在承诺解析代码中使用 data.json()。
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);
}
}
我正在尝试通过 http 调用请求网页并获取数据。
我可以使用 chrome 插件避免跨域,但当我发出请求时,响应始终是 "null"。
如何在我的 angular 应用程序中获取 html 页面作为 json 对象?
ngOnInit(): void {
// Make the HTTP request:
this.http.get('http://www.hurriyet.com.tr/gundem/').subscribe(data => {
this.results = data;
});
}
您应该确保请求 URL 以 .json 结尾,例如:
http://www.hurriyet.com.tr/gundem/gundem.json
这将自动对 mime 类型进行排序。像这样:
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'];
});
您可能还需要在承诺解析代码中使用 data.json()。
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);
}
}