我读了几个关于同一个问题的问题,但没有找到答案。我尝试使用web服务来显示角度组件中的数据。为此,我创建了模型、服务和组件。我习惯于用旧的HttpClient构建这样的请求。
这是我的模型,它定义了字段。
export class CryptoCurrency {
constructor(private _id: number,
private _currencyKeyId: string,
private _currencyname: string,
private _symbol: string,
private _isPublic: boolean) {
}我构建了一个基本的json文件,其中包含要检索(json-server)服务层的一些数据:
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;
});
}
}我在HttpClientModule中声明了app.component.ts
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>发布于 2020-01-20 14:26:29
您只需将服务中的HttpClientModule替换为
import { HttpClient } from '@angular/common/http';在构造函数中:
private http: HttpClient如果您注意到在文档中,您只初始化应用程序组件中的HttpClientModule。
发布于 2020-01-20 14:23:10
您不应该在服务中依赖HttpClientModule,它应该只在您的模块导入中。将CryptoCurrencyService改为依赖HttpClient。
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }https://stackoverflow.com/questions/59825180
复制相似问题