首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >subscribe on observable问题

subscribe on observable问题
EN

Stack Overflow用户
提问于 2018-12-11 09:18:12
回答 1查看 35关注 0票数 0

我有以下代码作为服务的一部分:

代码语言:javascript
复制
return this.httpClient.get<Country[]>('http://localhost:8080/countries');

它使用模拟的值通过了单元测试。但是,当在ngOnInit()函数中使用时,它不会将相关的值赋给变量。

代码语言:javascript
复制
this.supportedCountriesFetcherService.fetchSupportedCountries().subscribe((data) => (this.supportedCountries = data));

我已经用邮递员和本地主机返回相关的json进行了测试。如果我记录subscribe的数据,而不是赋值它,就不会返回记录的数据(实际上,要么添加空白日志,要么根本不添加)。

如何解决此问题?

编辑:

服务相关代码(无接口):

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

组件相关代码:

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

}
EN

回答 1

Stack Overflow用户

发布于 2018-12-11 09:52:39

您可能会在http请求中收到错误。尝试更改您的订阅以添加错误处理程序,如下所示:

代码语言:javascript
复制
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开发服务器代理的官方文档

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53716026

复制
相关文章

相似问题

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