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

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

问题描述

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

import { Component, OnInit } from '@angular/core';import { Observable, of } from 'rxjs';从@angular/common/http"导入 { HttpHeaders, HttpClient };import { catchError, map } from 'rxjs/operators';@成分({选择器:'app-treeview-tab',templateUrl: './treeview-tab.component.html',styleUrls: ['./treeview-tab.component.scss']})导出类 TreeviewTabComponent 实现 OnInit {构造函数(私有客户端:HttpClient){}http选项 = {标头:新 HttpHeaders({ 'Content-Type': 'application/json' })};/*** 处理失败的 Http 操作.* 让应用程序继续运行.* @param operation - 失败的操作名称* @param result - 作为可观察结果返回的可选值*/私有句柄错误(操作 = '操作',结果?:T){返回(错误:任何):Observable=>{//TODO: 将错误发送到远程日志记录基础设施控制台错误(错误);//改为登录到控制台//TODO:更好地为用户消费转换错误this.log(`${operation} 失败:${error.message}`);//通过返回空结果让应用程序继续运行.返回(结果为 T);};}/*** 记录失败的 AviorBackend 错误.* @param message - 失败操作的消息*/私人日志(消息:字符串){throw new Error(`AviorBackend: ${message}`);}//应该从 API 中获取节点 = [];选项 = {};ngOnInit() {//获取JSONconst API_URL = 'localhost:3000/gettreeview';返回 this.client.get(API_URL, this.httpOptions).pipe(地图((资源:响应)=> {this.nodes = res ||{};}),catchError(this.handleError()));}}

我收到以下错误消息:

输入'响应|{}' 不可分配给类型 'any[]'.类型 'Response' 缺少来自类型 'any[]' 的以下属性:length、pop、push、concat 和 26 个更多.

更新我的模板.html:

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

解决方案

尝试:

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

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

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())
  );
  }
}

I am getting the following error message:

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.

UPDATE my template.html:

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

解决方案

Try:

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

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

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

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