首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度应用中的观测值处理

角度应用中的观测值处理
EN

Stack Overflow用户
提问于 2017-08-29 15:22:04
回答 1查看 34关注 0票数 0

我有一个角度应用程序,在这个应用程序中,我使用RxJ库从后端API服务器获取数据。电话看起来是这样的:

代码语言:javascript
复制
allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] {
    const self = this;
    const path = `/powerPlants?onlyActive=${onlyActive}&page=${page}`;
    this.apiService.get(path).subscribe(
      powerplants => {
      powerplants.map(item => {
        if (this.isPowerPlant(item)) {
          // make the item an instance of PowerPlant
          self.powerPlants.push(item as PowerPlant);
        }
      });
    },
    err => {
        console.log('oops **** some error happened');
      // handle error
    });
    return this.powerPlants;
  }

我现在有以下问题:

  1. 我返回数组的方式理想吗?在我所做的那一行: 返回this.powerPlants

powerPlants是包含此方法的类中的一个数组!

  1. 我所做的是,我刚刚启动了我的角度应用程序,但后端API服务器并没有在我的机器上本地运行。当我在浏览器上访问我的应用程序时,我注意到我的应用程序不断地调用后端API服务器。我怎么才能避免这种情况?为什么这个应用会打那么多的电话,每次回电话都是404!过了一段时间,我可以在浏览器控制台中看到它对后端API服务器进行了超过10000次HTTP调用,每次调用都返回了404!
  2. HTTP方法选项将被执行,而不是GET!为什么会这样呢?我知道这必须要使用CORS过滤器,我已经在后端API服务器上启用了这个过滤器!
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-29 15:38:00

下面是你问题的答案。

  • 我返回数组的方式理想吗?在我所做的行中:No 把this.powerPlants还给谁?这不是所谓的函数什么的。您正在订阅可观察到的数据,现在您需要在您的应用程序中使用它。

您可以使用Observable.map,以防您想要发送数据--其他人可以订阅它,

代码语言:javascript
复制
allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] {
    const self = this;
    const path = `/powerPlants?onlyActive=${onlyActive}&page=${page}`;
    this.apiService.get(path).map(
      powerplants => {
      powerplants.map(item => {
        if (this.isPowerPlant(item)) {
          // make the item an instance of PowerPlant
          self.powerPlants.push(item as PowerPlant);
        }
      });
    },
    err => {
        console.log('oops **** some error happened');
      // handle error
    });
    return this.powerPlants;
  }
  • 对于问题2,您可以在数组不为空或数据不可用的情况下进行某种检查,而不是调用服务器。
  • HTTP方法选项将被执行,而不是GET!为什么会这样呢?我想它总是打个电话来检查标题。不太确定。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45942875

复制
相关文章

相似问题

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