首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角8: this.http.get不是函数

角8: this.http.get不是函数
EN

Stack Overflow用户
提问于 2020-01-20 14:19:30
回答 2查看 466关注 0票数 1

我读了几个关于同一个问题的问题,但没有找到答案。我尝试使用web服务来显示角度组件中的数据。为此,我创建了模型、服务和组件。我习惯于用旧的HttpClient构建这样的请求。

这是我的模型,它定义了字段。

代码语言:javascript
复制
export class CryptoCurrency {
  constructor(private _id: number,
              private _currencyKeyId: string,
              private _currencyname: string,
              private _symbol: string,
              private _isPublic: boolean) {
  }

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

代码语言:javascript
复制
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);
  }
}

在我的部分:

代码语言:javascript
复制
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;
    });
  }
}

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

代码语言:javascript
复制
import { HttpClientModule } from '@angular/common/http';

在进口方面:

代码语言:javascript
复制
  imports: [
    NgbModule,
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule
  ],

最后,在html文件中:

代码语言:javascript
复制
  <ul>
    <li *ngFor="let currency of currencies">
      {{ currency.id }} {{ currency.currencyKeyId}} {{ currency.symbol}} {{ currency.currencyname}}
    </li>
  </ul>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-20 14:26:29

您只需将服务中的HttpClientModule替换为

代码语言:javascript
复制
import { HttpClient } from '@angular/common/http';

在构造函数中:

代码语言:javascript
复制
private http: HttpClient

如果您注意到在文档中,您只初始化应用程序组件中的HttpClientModule。

票数 2
EN

Stack Overflow用户

发布于 2020-01-20 14:23:10

您不应该在服务中依赖HttpClientModule,它应该只在您的模块导入中。将CryptoCurrencyService改为依赖HttpClient

代码语言:javascript
复制
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59825180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档