Jagruti
Jagruti

Reputation: 43

Iterate through an array of objects Angular 2 component

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);
}

Upvotes: 1

Views: 2180

Answers (3)

Nick G.
Nick G.

Reputation: 111

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

  }

}

Upvotes: 1

Pezetter
Pezetter

Reputation: 2862

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.

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658225

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.

Upvotes: 0

Related Questions