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

时间:2016-08-04 07:48:39

标签: http angular rxjs observable

我不知道我做错了什么,但不知何故我无法读取数据,尽管数据来自服务器作为回应,甚至数据也显示在服务内部数据中方法当我把控制台但是在组件里面的订阅功能中时它给了我未定义的方法。帮助我做错了什么,我假设的是这是异步问题,但我不知道它是多么正确。 任何帮助都会很明显。 Thanx提前

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

2 个答案:

答案 0 :(得分:6)

listByEmpId(empId:string){

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

答案 1 :(得分:3)

这可能是因为您在从服务实际返回数据之前尝试访问您的allocatedAssetsLists。

如果您在模板中访问它,则可以使用简单的ngIf来确保只在数据可用时才显示它。

如果不是这样,我们需要更多关于您的问题的信息来提供帮助。