简体   繁体   English

使用Observable的Angular2 HTTP订阅显示未定义的数据

[英]Angular2 HTTP using observables subscribe showing data undefined

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. 我不知道自己在做错什么,但是以某种方式我无法读取数据,尽管当我放入控制台时,数据是作为响应来自服务器的,甚至数据也已显示在服务extractData方法中,但是在订阅函数内部的组件中,它给了我未定义的信息。 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 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);
    }
}
listByEmpId(empId:string){

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

This is probably because you are trying to access your allocatedAssetsLists before the data is actually returned from the service. 这可能是因为您试图在实际从服务返回数据之前访问您的locatedAssetsLists。

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. 如果要在模板中访问它,则可以使用简单的ngIf来确保仅在数据可用后才尝试显示它。

If this is not it, we need more information on your problem to help. 如果不是这样,我们需要有关您的问题的更多信息以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM