5

I don't know what I'm doing wrong but somehow i'm not able to read data, though the data is coming from server in response and even the data is getting showed inside service extractData method when I'm putting the console but in component inside subscribe function it is giving me undefined. Help me what I'm doing wrong, what I'm assuming is that this is the problem of async but, I have no idea how correct it. Any help will be appreciable. Thanx in advance

Component.ts

import { Component, Input, OnInit } from '@angular/core';
import {AdminService} from './admin.service';
import {logistics} from '../shared/model/logistics';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import { Observable }     from 'rxjs/Observable';
import {Response } from '@angular/http';
@Component({
    moduleId:module.id,
    selector: 'admin',
    templateUrl: 'admin.component.html',
    styleUrls:['admin.component.css'],
    providers:[AdminService]
})

export class AdminComponent implements OnInit{
   @Input() public allocatedAssetsList: logistics[];


    mode = 'Observable';
    public errorMsg = '';
    constructor(private adminService: AdminService) {

    }

    ngOnInit(){
        this.listByEmpId("123");

    }

    listByEmpId(empId:string){

        this.adminService.getAllocatedAssets(empId).subscribe(
        res => this.allocatedAssetsList = res,
        error =>  this.errorMessage = <any>error);
    }
}

Service.ts

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Hero }           from './hero';
import { Observable }     from 'rxjs/Observable';
import { Headers, RequestOptions } from '@angular/http';
import {logistics} from '../shared/model/logistics';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class AdminService {
    constructor (private http: Http) {}
    private listAssetsURL = '/api/logistics/list/';  // URL to web API

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

    getAllocatedAssets (empId: string): Observable<logistics[]> {

        this.listAssetsURL+= empId;
        //let body = JSON.stringify({ empId });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.get(this.listAssetsURL)
            .map(this.extractData)
            .catch(this.handleError);
    }
}
5
  • Where exactly do you get undefined? Commented Aug 4, 2016 at 8:08
  • @GünterZöchbauer Below is the function in component.ts file, I've added the log line and it shows undefined. listByEmpId(empId:string){ this.adminService.getAllocatedAssets(empId).subscribe( res => this.allocatedAssetsList = res, error => this.errorMessage = <any>error); console.log(JSON.stringify(this.allocatedAssetsList)); } Commented Aug 4, 2016 at 8:18
  • Can you please add a console.log(...) where and how exactly you checked? Commented Aug 4, 2016 at 8:19
  • @GünterZöchbauer I'm new to angular2 so, m not exactly sure whether its right what m doing. how to fetch data in subscribe. Commented Aug 4, 2016 at 8:21
  • I updated my answer. Please edit your code accordingly and please tell what is printed. Commented Aug 4, 2016 at 8:24

2 Answers 2

6
listByEmpId(empId:string){

    this.adminService.getAllocatedAssets(empId).subscribe(
    res => {
      this.allocatedAssetsList = res;
      console.log(this.allocatedAssetsList);
    },
    error =>  this.errorMessage = <any>error);
}
Sign up to request clarification or add additional context in comments.

1 Comment

extractData method which is inside service.ts file is showing the data accurately but problem is in component.ts file data is coming undefined. can you look in to component code and tell what m doing wrong in subscribe function.
3

This is probably because you are trying to access your allocatedAssetsLists before the data is actually returned from the service.

If you are accessing it in your template you can use a simple ngIf to make sure you only try to display it once the data is available.

If this is not it, we need more information on your problem to help.

2 Comments

Hi, exactly I'm also assuming that too i.e., because my log inside component file is getting printed first than service file logs. But this is the problem I don't know how to handle this async I thought the subscribe will do it for me. But now m stucked
I have this same problem too. No one has indicated whether the code is wrong (my code is just like the done in the question). I know that you can use the elvis operator (?) in your html, but what about when you need to work on the data in your typescript file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.