如何提取返回数组的数组中的值-HttpClient服务-Angular 7+

时间:2018-11-13 15:22:40

标签: angular rxjs pipe observable angular-httpclient

从Angular 7+中的Http请求返回数据后,我很难掌握如何管理数据

获取每个位置的服务如下:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Base } from '../interfaces/base';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BaseService {

  base$: Observable<Base[]>;

  constructor(private http: HttpClient) { }

  getAllBases() {
    const token = localStorage.getItem('access_token');
    return this.http.get(
      'https://megaphone-test.herokuapp.com/api/base/getAllBases',
      {
        headers: new HttpHeaders().append('x-access-token', token)
      }
    );
  }
}

我正在像这样的组件中使用它(现在这是一个很大的失败)为了简洁起见,我没有发送整个文档,但是肉和土豆就在这里:

export class TreeComponent implements OnInit {
  @Input() node: string;
  base$: Base[];
  loading: boolean;

  constructor(public baseService: BaseService) { }

  ngOnInit() {
    this.loading = true;
    this.baseService.getAllBases()
    .subscribe(
      res => {
        this.base$ = res['bases'];
      }
    );
  }

}

如果我在控制台中记录该响应并在控制台中查看,则会将两个数组塞入一个父数组中。因此,res ['bases']当然看起来像:

(2) [{…}, {…}]0: {id: 1, basePhoneNumber: "+18442367381", baseName: "Test AFB 1", bandwidthUserId: "u", bandwidthApiToken: "t", …}1: {id: 2, basePhoneNumber: "+12345678908", baseName: "Test AFB 2", bandwidthUserId: "u", bandwidthApiToken: "t", …}length: 2__proto__: Array(0)

所以我要努力理解的是如何将这些数据放入可以使这项工作有效的数据中?

<ng-container [clrLoading]="loading">
    <clr-tree-node *ngFor="let base of base$">
        <!-- {{ base?.baseName }} -->
        {{ base.baseName }}
    </clr-tree-node>
</ng-container>

1 个答案:

答案 0 :(得分:0)

哦,我的

我今天简直就是错过了!我发现了导致问题的原因!

You see, I am using the Clarity UI framework.

因此使用树形视图的示例显示:

import {Component, Input, OnInit} from "@angular/core";

@Component({
    selector: "lazy-loaded-locations",
    template: `
        <ng-container [clrLoading]="loading">
            <clr-tree-node *ngFor="let location of locations">
                {{location}}
            </clr-tree-node>
        </ng-container>
    `
})
export class LazyLoadedLocationsComponent implements OnInit {
    @Input() node: string;
    locations: string[];
    loading: boolean;

    ngOnInit() {
        this.loading = true;
        // This would be a call to your service that communicates with the server
        this.locations = fetchLocations();
    }
}

所以我做错了没有在进行API调用后将加载状态设置为false。一旦我将其设置为false,碱基名称就出现了!感谢您抽出宝贵的时间和我一起检查。现在感觉像真正的普茨机。

干杯

艾伦教练