Angular 2 个带有 Observables 的 Http 请求。如何使用 .subscribe 处理数据
Angular 2 Http request with Observables. How to process data with .subscribe
我正在使用 angular 2 编写一个网络应用程序,并且有一个基于 nodejs/express 的 API。
我已经完成身份验证,运行 现在我想从 API 查询数据,工作正常。
API 从远程服务器获取信息并发送一个 json 数组,如下所示: { "option1": "value1", "option2", "value2", ... }
这就是我的麻烦开始的地方。我可以毫无问题地获取数据并通过 angular 和 this.apiService.get('serverinfo').subscribe(console.log(response));
在我的控制台中打印它们,但即使我尝试正确写入变量也无法在其他任何地方访问它们。
到目前为止,这是我的代码:
api.service.ts:
import { Injectable } from '@angular/core';
import { Headers, Http, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
//import { Observable } from 'rxjs/Observable';
export class Data {
}
// Import RxJs required methods
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
private getUrl = 'http://localhost:3000/api/get/';
constructor(private http: Http) { }
get(what): Observable<Data[]> {
var token = JSON.parse(localStorage.getItem('id_token'));
return this.http
.get(this.getUrl + what + '?token=' + token.token)
.map(this.extractData)
.catch(this.handleError);
//response => response.json() as Data[]
}
// localStorage.setItem('id_token', JSON.stringify({ token: body.token }));
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
overview.component.ts:
import { Component, OnInit } from '@angular/core';
import { ApiService, Data } from '../services/api.service'
@Component({
selector: 'overview',
templateUrl: './overview.component.html',
styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit {
constructor(public apiService: ApiService) { }
data: Data = {};
ngOnInit() { this.getData() }
getData() {
this.apiService.get('serverinfo').subscribe(console.log(response)); // Logs data correctly to console
/*.subscribe( response => this.data = response )*/ // Can't access data from this one
console.log(this.data)
}
}
我认为这可能是数据类型的原因,我看到示例是数据中的所有选项都在那里预先配置,但我不能在这里真正这样做,因为我有非常大的对象而且这些不会总是相同的结构。
你的数据是一个对象:data: Data = {};
但是你得到的是 return 一个数组:get(what): Observable<Data[]>
试试这个:data: Data[] = [];
我正在使用 angular 2 编写一个网络应用程序,并且有一个基于 nodejs/express 的 API。
我已经完成身份验证,运行 现在我想从 API 查询数据,工作正常。
API 从远程服务器获取信息并发送一个 json 数组,如下所示: { "option1": "value1", "option2", "value2", ... }
这就是我的麻烦开始的地方。我可以毫无问题地获取数据并通过 angular 和 this.apiService.get('serverinfo').subscribe(console.log(response));
在我的控制台中打印它们,但即使我尝试正确写入变量也无法在其他任何地方访问它们。
到目前为止,这是我的代码:
api.service.ts:
import { Injectable } from '@angular/core';
import { Headers, Http, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
//import { Observable } from 'rxjs/Observable';
export class Data {
}
// Import RxJs required methods
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
private getUrl = 'http://localhost:3000/api/get/';
constructor(private http: Http) { }
get(what): Observable<Data[]> {
var token = JSON.parse(localStorage.getItem('id_token'));
return this.http
.get(this.getUrl + what + '?token=' + token.token)
.map(this.extractData)
.catch(this.handleError);
//response => response.json() as Data[]
}
// localStorage.setItem('id_token', JSON.stringify({ token: body.token }));
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
overview.component.ts:
import { Component, OnInit } from '@angular/core';
import { ApiService, Data } from '../services/api.service'
@Component({
selector: 'overview',
templateUrl: './overview.component.html',
styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit {
constructor(public apiService: ApiService) { }
data: Data = {};
ngOnInit() { this.getData() }
getData() {
this.apiService.get('serverinfo').subscribe(console.log(response)); // Logs data correctly to console
/*.subscribe( response => this.data = response )*/ // Can't access data from this one
console.log(this.data)
}
}
我认为这可能是数据类型的原因,我看到示例是数据中的所有选项都在那里预先配置,但我不能在这里真正这样做,因为我有非常大的对象而且这些不会总是相同的结构。
你的数据是一个对象:data: Data = {};
但是你得到的是 return 一个数组:get(what): Observable<Data[]>
试试这个:data: Data[] = [];