Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subscribe in Angular 2

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:)

  1. 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.

like image 416
Serhiy Avatar asked Jan 05 '23 22:01

Serhiy


1 Answers

You probably want to execute this.viewNodes when the request returns a value and not execute the result of this.viewNodes()

This

this.structureRequest.sendRequest().subscribe( this.viewNodes());

should be changed to

this.structureRequest.sendRequest().subscribe(() => this.viewNodes());

The former executs this.viewNodes() and passes the result to subscribe(), the later creates a new inline function which is passed to subscribe(). This inline function, when called, executes this.viewNodes()

If you want to pass the value sendRequest() returns it should be

this.structureRequest.sendRequest().subscribe((result) => this.viewNodes(result));

update

sendReqeust() doesn't return anything.

It should be

return this.http.get(this.myUrl, options) ...

but this only works the way you use it in your code if it returns an Observable.

but the subscribe() at the end returns a Subscription

 return this.http.get(this.myUrl, options)
    .map((res: Response) => res.json())
    .subscribe(res => {this.result = res;
        return this.result; });

therefore this should be changed to

 return this.http.get(this.myUrl, options)
    .map((res: Response) => res.json())
    .map(res => {
      this.result = res;
      return this.result; 
    });

or

 return this.http.get(this.myUrl, options)
    .map((res: Response) => res.json())
    .do(res => {
      this.result = res;
    });

The difference is that do() doesn't modify the value of the stream and doesn't need to return anything. The value returned from .map() will be forwarded. Ensure do is imported (like map) if you want to use it.

like image 173
Günter Zöchbauer Avatar answered Jan 15 '23 13:01

Günter Zöchbauer