使用 angular 6 get 请求从网站中提取数据

Pulling data from website with angular 6 get requests

我正在尝试从网上提取 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 不起作用,但我不明白为什么。

在这里你必须在你的构造函数中初始化 http 如下:

constructor(private httpClient: HttpClient) { }

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

@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);
  }
}

让 angular 在构造函数中执行此操作只是以下操作的快捷方式:

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