Angular 8:this.http.get不是一个函数

问题描述 投票:1回答:1

我阅读了有关同一问题的几个问题,但没有找到答案。我尝试使用Web服务以角度组件显示数据。为此,我创建了一个模型,服务和组件。我曾经用旧的HttpClient建立这样的请求。

这是我的定义字段的模型。

export class CryptoCurrency {
  constructor(private _id: number,
              private _currencyKeyId: string,
              private _currencyname: string,
              private _symbol: string,
              private _isPublic: boolean) {
  }

我建立了一个基本的json文件,其中包含一些要检索的数据(json服务器)服务层:

import { Injectable } from '@angular/core';
import {CryptoCurrency} from '../../model/crypto-currency/CryptoCurrency.model';
import { HttpClientModule} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CryptoCurrencyService {
  baseUrlBackend = 'http://localhost:3000/currencies';

  constructor(private http: HttpClientModule) { }

  getAll() {
    return this.http.get<Array<CryptoCurrency>>(this.baseUrlBackend);
  }
}

在我的组件中:

import { Component, OnInit } from '@angular/core';
import {CryptoCurrency} from '../../shared/model/crypto-currency/CryptoCurrency.model';
import {CryptoCurrencyService} from '../../shared/services/crypto/CryptoCurrency.service';

@Component({
  selector: 'app-currencies',
  templateUrl: './currencies.component.html',
  styleUrls: ['./currencies.component.css'],
  providers: [ CryptoCurrencyService ]
})
export class CurrenciesComponent implements OnInit {
  currency: CryptoCurrency;
  currencies: Array <CryptoCurrency> = [];

  // dependency injection
  constructor(private cryptoCurrencyService: CryptoCurrencyService ) { }

  ngOnInit() {
    this.cryptoCurrencyService.getAll().subscribe(res => {
      this.currencies = res;
    });
  }
}

我在app.component.ts中声明了HttpClientModule

import { HttpClientModule } from '@angular/common/http';

并且在导入中:

  imports: [
    NgbModule,
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule
  ],

最后在html文件中:

  <ul>
    <li *ngFor="let currency of currencies">
      {{ currency.id }} {{ currency.currencyKeyId}} {{ currency.symbol}} {{ currency.currencyname}}
    </li>
  </ul>
angular rest
1个回答
0
投票

您不应该依赖service中的HttpClientModule,它只能位于module导入中。更改CryptoCurrencyService以改为依赖HttpClient

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

constructor(private http: HttpClient) { }
© www.soinside.com 2019 - 2024. All rights reserved.