如何将HttpClient GET获取的数据存储到变量中? [英] How to store HttpClient GET fetched data into a variable?

查看:53
本文介绍了如何将HttpClient GET获取的数据存储到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My Backend over at localhost:3000/gettreeview returns a JSON object and it needs to be stored in the variable nodes. I tried to accomplish it with the code below but have failed:

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:

UPDATE my template.html:

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

推荐答案

尝试:

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

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

You also need to remove the return as you aren't returning anything from the ngOnInit() hook.

这篇关于如何将HttpClient GET获取的数据存储到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆