【发布时间】:2016-10-09 19:08:36
【问题描述】:
我希望我的 ngOnInit 函数执行以下操作: - 使用 this.structureRequest.sendRequest() 对一些数据进行 http 请求,它工作正常,并且在收到数据后使用 this.viewNodes() 函数开始查看它。 我使用 subscribe ,但它不起作用,我认为我在 subscribe 功能上做错了。请帮忙:)
-
HomeComponent.ts
import {Component} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {StructureRequestService} from './StructureRequestService'; export class Content { ok: boolean; content = []; } @Component({ providers: [StructureRequestService], styleUrls: ['app/home/home.css'], templateUrl:'./app/home/homePageTemplate.html' }) export class HomeComponent { contentArray = []; myRes: Content; showAssigned:boolean = false; showSubitems:boolean = false; showUsers:boolean = false; constructor(private structureRequest: StructureRequestService) {} ngOnInit() { this.structureRequest.sendRequest().subscribe( this.viewNodes()); } viewNodes() { this.myRes = this.structureRequest.result; this.contentArray = this.myRes.content; this.showAssigned = true; } }
2.这里是http服务,http get工作正常,收到所有数据:
import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
@Injectable ()
export class StructureRequestService {
result: Object;
//private myUrl = 'http://manny.herokuapp.com/audit/get/structure';
private myUrl = './app/home/nodes.json'; // local URL to structure APi
constructor (private http: Http) {
//use XHR object
let _build = (<any> http)._backend._browserXHR.build;
(<any> http)._backend._browserXHR.build = () => {
let _xhr = _build();
_xhr.withCredentials = true;
return _xhr;
};
}
sendRequest() {
let body = JSON.stringify({});
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({
headers: headers
});
this.http.get(this.myUrl, options)
.map((res: Response) => res.json())
.subscribe(res => {this.result = res;
return this.result; });
}
}
3.所以问题是同步步骤:接收数据,而不是查看它。
【问题讨论】: