I want my ngOnInit function do next things: - make http request for some data using this.structureRequest.sendRequest(),which works fine, and after data have been received to start view it using this.viewNodes() function. I use subscribe , but it does not work, I think I do something wrong with subscribe function. please help:)
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.Here is http service, http get works fine, all data received:
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.so the problem is to make synchronous steps: receive data, than view it.