首页 > 解决方案 > 如何将 HttpClient GET 获取的数据存储到变量中?

问题描述

我的后端localhost:3000/gettreeview返回一个 JSON 对象,它需要存储在变量中nodes。我试图用下面的代码来完成它,但失败了:

import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';

@Component({
  selector: 'app-treeview-tab',
  templateUrl: './treeview-tab.component.html',
  styleUrls: ['./treeview-tab.component.scss']
})
export class TreeviewTabComponent implements OnInit {
  constructor(private client: HttpClient) {  }
  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };
  /**
 * Handle Http operation that failed.
 * Let the app continue.
 * @param operation - name of the operation that failed
 * @param result - optional value to return as the observable result
 */
private handleError<T>(operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // TODO: better job of transforming error for user consumption
    this.log(`${operation} failed: ${error.message}`);

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}
 /**
   * Log a failed AviorBackend error.
   * @param message - message of the operation that failed
   */
  private log(message: string) {
    throw new Error(`AviorBackend: ${message}`);
  }


  // should be fetched from API
  nodes = [];
  options = {};
  ngOnInit() {

 //get JSON 
  const API_URL = 'localhost:3000/gettreeview';
  return this.client.get(API_URL, this.httpOptions).pipe(
    map((res: Response) => {
      this.nodes = res || {};
    }),
    catchError(this.handleError())
  );
  }
}

我收到以下错误消息:

Type 'Response | {}' is not assignable to type 'any[]'.
  Type 'Response' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.

更新 我的 template.html:

<tree-root [nodes]="nodes" [options]="options" (click)="test()" class="list-area"></tree-root>
<div id="treeuserdata" class="content-area"> </div>

标签: jsonangularangular-httpclientangular-tree-component

解决方案


尝试:

this.client.get(API_URL, this.httpOptions).subscribe(
  (res) => { this.nodes.push(res) },
  (error) => { this.handleError(); }
);

您还需要删除,return因为您没有从ngOnInit()钩子中返回任何内容。


推荐阅读