【问题标题】:Angular 4 how to request a web page content as a json objectAngular 4如何将网页内容请求为json对象
【发布时间】:2017-09-08 08:53:36
【问题描述】:

我正在尝试通过 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;
    });
}

【问题讨论】:

  • 为什么你期望 data 是一个带有 results 属性的对象? this.http 的类型是什么?
  • 我的错,已更正...
  • 那么现在,什么是 null?您在哪里记录/显示响应以确定它为空?再说一遍,this.http 的类型是什么?
  • 我在其他地方记录“this.results”.. 我不认为 console.log 部分那么重要:)) 响应为空.. 这里数据是我的响应.. http 来自@angular/http,我不确定我是否理解了这个问题..
  • 这很重要。

标签: angular angular2-http webharvest angular-httpclient


【解决方案1】:

您应该确保请求 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()。

【讨论】:

    【解决方案2】:
    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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 2020-10-24
      • 1970-01-01
      • 2019-07-12
      • 2018-06-27
      • 1970-01-01
      • 2018-02-23
      • 2019-10-24
      • 1970-01-01
      相关资源
      最近更新 更多