1

Can anyone help what I am doing incorrect, anything missing? I am getting undefined for --'this.ack.length'

this._activeChannelService.requestChannelChange(this.selectedchannel.channelName)
        .subscribe(
            ack  => {
                this.ack= ack;
                console.log(" test:  ", this.ack.length);
            },
            err => {
            console.log(err);
        });enter code here

ack is of time ack:Iack[];

Iack has two field of type string. result and message I need to iterate through array of Iack[] to get the result and message if message=success then call the another service

service

requestChannelChange (name: string): Observable<Iack[]> {
    alert('in servicerequestChannelChange');
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    let postchannelname = "channelName=" + name;
    let requestt = new IRequest(name);
    console.log(JSON.stringify(requestt));
    return this._http.post(this._activateChangeUrl, JSON.stringify(requestt),{ headers: headers })
     //.map(this.extractData)
        .map((res:Response) => res.json() as Iack[])
        .do(data => console.log("All: " + JSON.stringify(data)))
     .catch(this.handleError);
}
5
  • Can you provide us content of _activeChannelService? Commented Dec 21, 2016 at 14:02
  • echonax- I just updated the quesion to provide ack. Commented Dec 21, 2016 at 14:07
  • – Matej Maloča - I have updated toprovide service content Commented Dec 21, 2016 at 14:10
  • I can see ask is coming and being printed on the console Commented Dec 21, 2016 at 14:10
  • the JSON printed on console is All: {"result":"Channel Change","message":"ERROR"} Commented Dec 21, 2016 at 14:13

3 Answers 3

1

You can use observable in your TS service:

import { Injectable } from '@angular/core';
import { IPost } from './IPost';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';


@Injectable()
export class PostServices {

    private _webApiBaseUrl = "http://localhost:62806/v1/Posts"
    private _http : Http;

    constructor(http : Http){
        this._http = http;
    }   

    getAll(): Observable<IPost[]> {
        return this._http.get(this._webApiBaseUrl + '/all', this.getHeaders())
        .map((response: Response) => response.json())
        .do(data => console.log(`All Data: \n ${ JSON.stringify(data) }`))
        .catch(this.handleError);
    }   

    private handleError(error: Response){
        console.error(error);
        return Observable.throw(error.json().error || 'Server Error');
    }    

    private getHeaders()
    {
        let headers = new Headers();
        headers.append("Authorization", ""); 
        headers.append("Content-Type", "application/json");
        return new RequestOptions({ headers: headers });
    }

}

Usage in your TS class:

import { Component, OnInit } from '@angular/core';
import { IPost } from './IPost';
import { PostServices } from './posts.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

  posts: IPost[];
  errorMessage: string;

  private _postService: PostServices;
  constructor(postService: PostServices) {
    this._postService = postService;
  }


  ngOnInit() {
    this._postService.getAll()
      .subscribe(
      data => {this.posts = data; console.log("data.length: " + data.length)}, // here
      error => this.errorMessage = <any>error 
      );

  }

}
Sign up to request clarification or add additional context in comments.

Comments

0

enter code here is executed before this.ack= ack; is executed

This is a function

        ack  => {
            this.ack= ack;
            console.log(" test:  ", this.ack.length);
        }

that you pass to subscribe(...) and the observable calls it when the data arrives which can take a looong time when it's a call to a server.

enter code here is executed immediately.

12 Comments

appreciate your help.s there any way I can read the ack value after getting from service?
You can read it from within the callback, you can bind to it from the view (Angular updates the binding when the value becomes available, you can use ack?.someProp to avoid exceptions while the value is not yet available) You can use .map(...)` instead of .subscribe(...) and then use this.getChannel().subscribe(...) and access it there in the callback you pass to subscribe (assuming getChannel) is the name of the method that contains this._activeChannelService.requestChannelChange(...) - this needs to be prefixed with return to work)
can you please provide example of callback. also this contradict -- use .map instead of .subscribe? and then call back on .subscribe. Appreciate your help?
thanks for your help Günter Zöchbauer- its all fine now- thanks
|
0

You'll have to check for success within the service subscription. An observable is an asynchronous call, so any calls you want to make regarding the data in that async call must be made within it to remain a safe call.

So, make your seconds service call, within the subscription.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.