angular - 在 Angular 7 中,如何从 Observable 中提取结果?

标签 angular service observable angular7

我正在使用带有 Rail 5 后端的 Angular 7。我有一个用于与 Rails 5 后端交互的服务...

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class CurrencyService {
  constructor(private _http: HttpClient) { }

  index() {
    let ret = this._http.get<Object[]>('api/currencies').map(r => r);
    console.log(ret);
    return ret;
  }

  refresh() {
    return this._http.get<Object[]>('api/refresh').map(r => r);
  }
}

我在与服务交互的 src/app/app.component.ts 文件中有这个 ...

import { CurrencyService } from './../shared/currency.service';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  currencies = [];
  title = 'app';
  apiStatus: string;
  constructor(private _currencySrv: CurrencyService) { }

  ngOnInit() {
    this._currencySrv.index<Object[]>().subscribe(
      currencies => this.currencies = currencies);
  }

  refresh() {
    this._currencySrv.refresh<Object[]>().subscribe(
      currencies => this.currencies = currencies);
  }

}

如何从返回的 Observable 对象中提取调用“index”和“refresh”的结果?当我尝试使用 ngFor 遍历“货币”成员 var 时,出现错误

ERROR TypeError: Cannot read property 'name' of undefined
    at Object.eval [as updateRenderer] (AppComponent.html:4)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735)
    at checkAndUpdateView (core.js:13849)
    at callViewAction (core.js:14195)
    at execComponentViewsAction (core.js:14127)
    at checkAndUpdateView (core.js:13850)
    at callWithDebugContext (core.js:15098)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14635)
    at ViewRef_.detectChanges (core.js:11619)
    at eval (core.js:5918)

我认为是因为结果包含在一个名为“data”的字段中,但是当我尝试通过“ng serve”启动我的 Angular 服务器时,我不知道在没有各种编译错误的情况下提取该字段的正确方法。

编辑: 在 src/app/app.component.html 我有

<!--The content below is only a placeholder and can be replaced.-->
<ul>
  <ng-container *ngIf="currencies?.length">
  <li *ngFor="let currency of currencies">
    <div>{{currency.name}}</div>
    <div>{{currency.country}}</div>
    <div>{{currency.rate / 100}}</div>
  </li>
  </ng-container>
</ul>

刷新

虽然没有数据显示

最佳答案

您的代码中有很多问题需要更正。 @JBNizet 似乎已经提到了大部分问题。

让我们先从您的服务开始。

  • 如前所述,如果您在 Angular 应用程序中使用 rxjs6,则可以使用 rxjs6 管道运算符语法而不是 rxjs5 语法你用过。 (来源:docs)
  • Observableimport 位置更改为 rxjs 并将 map 更改为 rxjs/operators。 (来源:docs)
  • import { Http } from '@angular/http'; 是多余的。此软件包已弃用。请改用 @angular/common/http。 (来源:docs)
  • 不要使用 Object,因为它指的是非原始装箱对象。 (来源:docs)。而是使用 any 或更好的方法,创建一个定义后端响应的接口(interface)。
  • 您的 map 目前的编写方式,它甚至什么都不做。相反,由于您的后端返回一个包含 data 的对象,您可以使用 map 仅返回 data
  • 我不确定您的refresh api 是做什么的,但如果它只是获取与currencies api 相同的数据,那么似乎没有必要。我将在我的回答中保留它,因为我不确定它是否包含其他数据。

考虑到所有这些,您的 CurrencyService 现在看起来像

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { CurrenciesResponse, Currency } from 'path/to/your/interface';

@Injectable()
export class CurrencyService {
    constructor(
        private _http: HttpClient
    ) { }

    index(): Observable<Currency[]> {
        return this._http.get<CurrenciesResponse>('api/currencies').pipe(
            map((res: CurrenciesResponse) => res.data)
        );
    }

    refresh(): Observable<Currency[]> {
        return this._http.get<CurrenciesResponse>('api/refresh').pipe(
            map((res: CurrenciesResponse) => res.data)
        );
    }
}

你的界面看起来像这样

export interface CurrenciesResponse {
    data: Currency[];
    // Add other backend response properties here if present
}

export interface Currency {
    name: string;
    country: string;
    rate: number;
    // ...
}

将您的接口(interface)添加到单独的文件中,并在必要时导入它们。

在您的组件中,似乎只有一个问题。从 currencyService 调用 index()refresh() 时不需要提供类型参数,因为它们不是通用方法。您的 IDE 通常应该通过类似 Expected 0 type arguments, but got 1

的错误警告您
currencies: Currency[] = [];
title: string = 'app';
apiStatus: string;

constructor(
    private _currencySrv: CurrencyService
) { }

ngOnInit() {
    this._currencySrv.index().subscribe(currencies => {
        this.currencies = currencies;
    });
}

refresh() {
    this._currencySrv.refresh().subscribe(currencies => {
        this.currencies = currencies;
    });
}

最后,在您的 HTML 中,ngIf 是多余的,因为即使 ngFor 也不会打印任何内容,除非 currencies 包含数据。

<ul *ngFor="let currency of currencies">
    <li>
        <div>{{currency.name}}</div>
        <div>{{currency.country}}</div>
        <div>{{currency.rate / 100}}</div>
    </li>
</ul>

这是关于 StackBlitz 的工作示例.我用过angular-in-memory-web-api用于 API 响应。

关于angular - 在 Angular 7 中,如何从 Observable 中提取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57530201/

相关文章:

Angular 4 Firebase - Cloud Firestore 'Deeply Nested' 与 'Flatten'

java - getActivity() 在 Android java 服务中使用的其他方式

android - 在 android , JobScheduler 或使用计时器中哪种方式更好?

Android:将变量传递给已经运行的服务

angular - @ngrx/effects 给出 TypeError : You provided 'undefined' where a stream was expected. 您可以提供 Observable、Promise、Array 或 Iterable

具有多个客户端的 Web 应用程序数据库

angular - 如何将数据绑定(bind)到Angular2中的标签

Angular2 - 动态表单输入

ios - 如何使用从类函数编辑环境对象?

java - 使用 Retrofit 和 Observable 解析 REST 响应消息