如何将 HttpClient GET 获取的数据存储到变量中?
How to store HttpClient GET fetched data into a variable?
我的后端在 localhost:3000/gettreeview
returns 上有一个 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()
挂钩返回任何内容。
您需要订阅才能获得结果
.json() 不需要新的 angular 版本
return this.http.request(request)
.pipe(map(res => res) // you can map to anything you want here)
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('yay')
);
我的后端在 localhost:3000/gettreeview
returns 上有一个 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()
挂钩返回任何内容。
您需要订阅才能获得结果
.json() 不需要新的 angular 版本
return this.http.request(request)
.pipe(map(res => res) // you can map to anything you want here)
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('yay')
);