json - 如何将 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>
解决方案
尝试:
this.client.get(API_URL, this.httpOptions).subscribe(
(res) => { this.nodes.push(res) },
(error) => { this.handleError(); }
);
您还需要删除,return
因为您没有从ngOnInit()
钩子中返回任何内容。
推荐阅读
- javascript - 节点服务器在 Windows 10 中启动服务器花费了太多时间
- r - R 闪亮的反应单选按钮
- powerapps - 缺少使用 Sql 的默认电源应用程序的添加、编辑和删除功能
- javascript - 如何从 JSON fromat 中提取特定字段和值
- ubuntu - shell脚本中的monit命令
- performance - 针对特定设备的唯一 ID 的移动性能测试,这里我没有用户凭据,如何进行用户负载测试?
- gitahead - GitAhead 禁用 HTTPS 登录窗口
- c++ - ofstream不输出文件
- python - 在远程数据库服务器设置上实现 PostgreSQL 的性能
- testing - 是否可以使用 CANalyzer 将错误帧传输到总线上?