我正在尝试使用Service类获取JSON数据。 服务类
import { Injectable } from '@angular/core';
import { Http, HttpModule, Response } from '@angular/http';
import { GeneralTab } from './generalTab';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class GeneralTabService {
constructor(private _http : Http) {
console.log("Http call");
}
getStatus(): Observable<any> {
return this._http.get('http://samd.server.lan.at/taskmanagement/rest/taskconfigs/IND?language=EN&access_token=200')
.map((res:Response) => <GeneralTab[]>res.json())
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Observable.throw(errMsg);
}
}
组件类
import { Component, OnInit } from '@angular/core';
import {GeneralTab} from "./generalTab";
import {GeneralTabService} from "./generalTab.service";
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'general-tab',
templateUrl: '/general.component.html',
providers : [GeneralTabService]
})
export class GeneralComponent implements OnInit{
title = 'Serving data from General Component';
errorMessage: any;
status: GeneralTab [];
mode = 'Observable';
constructor (private generalService: GeneralTabService) {
this.status = [];
}
ngOnInit() {
console.log("Started");
this.generalService.getStatus().subscribe(
(status: any) => this.status = status,
(error: any) => this.errorMessage = error
);
console.log(this.status);
}
}
GeneralTab类
export class GeneralTab {
constructor(public recipientId : string,
public recipientName: string,
public recipientFullname: string,
public ouId:String,
public ouName:String,
public institute:number,
public shortName:String,
public status:String)
{
}
}
我在控制台中看到 .do(data =&gt; console.log(“All:”+ JSON.stringify(data)))正在获取像
这样的JSON数据{“subjectsConfig”:[{“subject”:“客户数据维护”,“预选”:false,“initialDueDate”:“2016-11-24”,“actionConfigs”:[{“action”:“SEND “ ”接收者“:[{ ”用户“:{ ”recipientId“: ”BD27A4F5923FCA13“, ”RECIPIENTNAME“: ”ABTABT“, ”recipientFullname“: ”ABTABT“, ”OUID“: ”BD27A4F5923FCA13“, ”ouName“:” 0015" ,...
订阅不会将任何数据分配给状态数组,而我正在获取空白的“状态”数组。我想将此数据作为状态变量中的数组用于测试目的。我怎么得到?
答案 0 :(得分:2)
如果您记录响应
console.log("Started");
this.generalService.getStatus().subscribe(
(status: any) => this.status = status,
(error: any) => this.errorMessage = error
);
console.log(this.status);
当然,由于上面的代码(getStatus().subscribe
)是异步的,因此您将看到空白状态。这意味着您正在提出请求,然后您正在等待subscribe
内的响应,当它到来时,您将status
分配给this.status
。在等待时,您已经记录了this.status
,这最初是空白的。
请尝试此操作并检查日志,
console.log("Started");
this.generalService.getStatus().subscribe(
(status: any) => {
this.status = status;
console.log(this.status);
},
(error: any) => this.errorMessage = error
);