angular - 组件调用httpget的subscribe方法后返回数据为Null
问题描述
这是我的组件文件:
import { Component, OnInit } from '@angular/core';
import { CclcService } from '../cclc.service';
import {HttpClient,HttpHeaderResponse,HttpClientModule} from '@angular/common/http';
import { ICurrencyData } from './ICurrencyData';
import { Currency } from './Currency';
@Component({
selector: 'app-cryto-currencies-list',
templateUrl: './cryto-currencies-list.component.html',
styleUrls: ['./cryto-currencies-list.component.css']
})
export class CrytoCurrenciesListComponent implements OnInit {
constructor(private cclcService: CclcService ) {
console.log('cclc component called');
}
public list : Currency;
ngOnInit() {
this.getCurrencyList();
}
public getCurrencyList()
{
this.cclcService.getCryptoCurrencyList().subscribe(data => {
console.log(data);
this.list = data;
console.log(this.list );
})
}
}
import { Injectable } from '@angular/core';
import {HttpClient,HttpHeaderResponse,HttpClientModule,HttpErrorResponse} from '@angular/common/http';
import { Observable } from "rxjs";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot,ActivatedRoute } from '@angular/router';
import { ICurrencyData } from './cryto-currencies-list/ICurrencyData';
import { Currency } from './cryto-currencies-list/Currency';
@Injectable({
providedIn: 'root'
})
export class CclcService {
private list : ICurrencyData[];
constructor(private httpClient:HttpClient ,private data:ICurrencyData,private resp: HttpHeaderResponse,private route:Router,actRoute:ActivatedRoute) {
console.log('cclc service constructor called');
resp.headers.set('Access-Control-Allow-Origin', '*');
}
private baseUrl = 'https://pro-api.coinmarketcap.com/';
private apiKey= 'bf8bbb9e-a227-46cb-862d-53a9ad3bbe51';
public getCryptoCurrencyList() : Observable<Currency>
{
return this.httpClient.get<Currency>(this.baseUrl +
'v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + this.apiKey)
console.log('service');
}
}
我正在使用 http 客户端模块通过服务调用 web api get 操作。但是在组件调用 subscribe 方法后,数据返回 null。当通过邮递员调用请求时,它工作得非常好。
理想情况下,它应该返回一个 json 结果。
但是当订阅请求成功完成时获取数据为空
cclc service constructor called
cryto-currencies-list.component.ts:18 cclc component called
cclc.service.ts:30 service
cclc.service.ts:31 Observable {_isScalar: false, source: Observable, operator: MapOperator}
cryto-currencies-list.component.ts:28 null
cryto-currencies-list.component.ts:30 null
解决方案
推荐阅读
- sql - PostgreSQL:使用 Generate_Series() 计数 0
- api - 如何在 DDD 中使用外部服务
- redis - Redis 在启动时立即达到最大客户数
- jmeter - Jmeter抛出CannotResolveClassException:com.zeroclue.jmeter.protocol.amqp.AMQPConsumer
- q# - Q#如何实现受控Hadamard?有内置功能吗?
- javascript - 如何正确比较数组元素的子串
- css - 链接垃圾邮件和我没有在 CSS 中编写的各种垃圾
- angular - Angular/Typescript 模型 - 如何组织
- amazon-web-services - 激活 Datapipeline 传递参数值
- c# - 我找不到的错误