我有以下代码作为服务的一部分:
return this.httpClient.get<Country[]>('http://localhost:8080/countries');它使用模拟的值通过了单元测试。但是,当在ngOnInit()函数中使用时,它不会将相关的值赋给变量。
this.supportedCountriesFetcherService.fetchSupportedCountries().subscribe((data) => (this.supportedCountries = data));我已经用邮递员和本地主机返回相关的json进行了测试。如果我记录subscribe的数据,而不是赋值它,就不会返回记录的数据(实际上,要么添加空白日志,要么根本不添加)。
如何解决此问题?
编辑:
服务相关代码(无接口):
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SupportedCountriesFetcherService {
public fetchSupportedCountries(): Observable<Country[]> {
return this.httpClient.get<Country[]>('http://localhost:8080/countries');
}
constructor(private httpClient: HttpClient) { }
}组件相关代码:
import { Component, OnInit } from '@angular/core';
import { Country, SupportedCountriesFetcherService } from 'src/app/services/supported-countries-fetcher.service';
@Component({
selector: 'app-input-form',
templateUrl: './input-form.component.html',
styleUrls: ['./input-form.component.css']
})
export class InputFormComponent implements OnInit {
private supportedCountries: Country[];
constructor(private supportedCountriesFetcherService: SupportedCountriesFetcherService) { }
ngOnInit() {
this.supportedCountriesFetcherService.fetchSupportedCountries()
.subscribe((data) => this.supportedCountries = data, (error) => console.log(error));
}
}发布于 2018-12-11 09:52:39
您可能会在http请求中收到错误。尝试更改您的订阅以添加错误处理程序,如下所示:
this.supportedCountriesFetcherService.fetchSupportedCountries()
.subscribe(
(data) => this.supportedCountries = data,
(err) => console.error(err);
);你应该会看到错误。
我假设您的Angular应用程序在端口4200上运行,这意味着除非您使用代理,否则您可能会收到CORS错误。
如果是这样的话,最简单的开发方法就是设置一个代理服务器。
您可以在https://angular.io/guide/build#proxying-to-a-backend-server上阅读有关设置webpack开发服务器代理的官方文档
https://stackoverflow.com/questions/53716026
复制相似问题