从角度6获取请求的网站中提取数据

时间:2018-06-20 15:37:39

标签: angular typescript angular-http

我正在尝试从网络上提取JSON文件,但我做错了什么。这是我的代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'

import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class PullanaliticsService {
  theUrl: string = 'https://jsonplaceholder.typicode.com/post';
  res = [];
  private httpClient: HttpClient;
  constructor() { }


  httpGetAsync()
  {
      var t = this.httpClient.get(this.theUrl).subscribe((res) => {
        console.log(res);
      });

      return t

}

(我将this.theUrl更改为每个人都可以查看的页面)

我遇到了错误:

DashboardComponent.html:4 ERROR TypeError: Cannot read property 'get' of undefined
    at `PullanaliticsService.push../src/app/pullanalitics.service.ts.PullanaliticsService.httpGetAsync (pullanalitics.service.ts:22)`

这听起来好像URL不起作用,但我不知道为什么。

2 个答案:

答案 0 :(得分:2)

在这里,您必须按照以下说明在构造函数中初始化http:

constructor(private httpClient: HttpClient) { }

答案 1 :(得分:1)

您的服务应已插入httpClient。您声明了它,但从未在代码中设置它的值。您可以通过在构造函数中提供http客户端,让angular为您设置该值。

@Injectable({
  providedIn: 'root'
})
export class PullanaliticsService {
  theUrl: string = 'https://jsonplaceholder.typicode.com/post';
  res = [];
  constructor(private httpClient: HttpClient) { }


  httpGetAsync() {
      return this.httpClient.get(this.theUrl);
  }
}

在构造函数中保留角度只是实现以下目的的快捷方式

export class PullanaliticsService {
  private httpClient: HttpClient;
  constructor(_httpClient: HttpClient) {
    this.httpClient = _httpClient;
  }
}